有100元,有50元,20元,10元,5元,1元的零钱,有多少中对换方法?
假设函数有f(100, 5)种对换方法,5表示5中面值,1-5分别对应1,5,10,20,50
然后进行分解,如果使用50的找零,先用一张50的,那么还能有f(50,5)中方法;
如果不使用50进行找零,就有f(100,4)种找法。
两种结果相加就得f(100,5)的解
书中源程序:
(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)))
(count-change 100)