看看SCIP里面有一个找零钱方式统计问题,觉得有趣自己做了一个迭代法求解,代码如下:
(define (count-change amount)
(define (first-amount k-of-cs)
(cond ((= k-of-cs 1) 1)
((= k-of-cs 2) 5)
((= k-of-cs 3) 10)
((= k-of-cs 4) 25)
((= k-of-cs 5) 50)))
(define (cc am k-of-cs cs)
(cond ((= am 0) (+ cs 1))
((or (< am 0) (= k-of-cs 0)) cs)
(else (cc am (- k-of-cs 1)
(cc (- am (first-amount k-of-cs)) k-of-cs cs)))))
(cc amount 5 0))
运算时觉得太慢了,决定用Perl重写了一个,对比一下
#!/usr/local/bin/perl
use strict;
use warnings;
my@firstmoney = (1,5,10,25,50);
my@cinfo = ();
my$amount = shift;
my$count = 0;
my$i = @firstmoney - 1;
while( $i >= 0 || @cinfo && $cinfo[0] >= 0 ) {
if( $i >= 0 ) {
$amount -= $firstmoney[$i];
if( $amount > 0 ) {
push @cinfo, $i;
} else {
do{$count++;print "第$count种情况: $firstmoney[$i]";print " $firstmoney[$_]" foreach(@cinfo);print "\n"} if $amount == 0;
$amount += $firstmoney[$i];
$i--;
}
} else {
$i = pop @cinfo;
$amount += $firstmoney[$i];
$i--;
}
}
print "共计$count种情况\n";