SCIP中关于找零钱方式统计的迭代解法

本文介绍了一种解决零钱找零问题的算法,并通过Scheme和Perl两种语言实现了该算法。作者首先使用Scheme语言实现了一个迭代法解决方案,然后为了提高效率,又用Perl进行了重写。Perl版本的代码通过循环和条件判断来计算不同面额硬币组合的数量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

看看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";


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值