SICP 之斐波那契数

这是斐波那契数 中用迭实现的

(define (fib n) (fib-iter 1 0 n))

(define (fib
-iter a b count)
(
if(= count 0)
b
(fib
-iter (+ a b) a (- count 1)))
)

下面关于它的应用 换零钱方式的统计

(define (count-change amount)
(cc amount
5)
)
(define (cc amount kinds
-of-coins)
(cond((
= amount 0) 1)
((
or (< amount 0)(= kinds-of-coins 0)) 0)
(
else (+ (cc amount (- kinds-of-coins 1))
(cc (
- amount (first-denomination kinds-of-coins))
kinds
-of-coins
)
))
)
)

(define (first
-denomination kinds-of-coins)
(cond ((
= kinds-of-coins 1) 1)
((
= kinds-of-coins 2) 5)
((
= kinds-of-coins 3) 10)
((
= kinds-of-coins 4) 25)
((
= kinds-of-coins 5) 50)
)
)

对于一种算法最关键的一点还是书上所说:如果a(为兑换的总额)为0的话,应该算作是有一种换零钱的方式!

如果a小于0的话应该算作有0中的换钱方式

如果n(为可以使用的兑换面额)为0的话,应该算作是有0种换零钱的方式!

其实,最关键的是第一点,一直挺想不通的,为什么,当兑换的面额为0的话,却又有一种换零钱的方式! 如果,没有这条的话,那么迭代是没有结果的!

上面的运行结果是 “292” !

据个人猜测最后应该是292 个1 相加的结果!

原文地址:https://www.cnblogs.com/neve/p/2015331.html