Exercise 1.14
Imports: [[Chapter 1.2]] count-change
(define (count-change amount)
(define (cc a n)
(cond ((< a 0) 0)
((= a 0) 1)
((= n 0) 0)
(else (+ (cc a (- n 1))
(cc (- a (first-denomination n)) n)))))
(cc amount 5))
(define (first-denomination kinds-of-coins)
(vector-ref '#(1 5 10 25 50) (- kinds-of-coins 1)))
(count-change 100) => 292
Here is the process generated by (count-change 11):
(cc 11 5)
(cc -39 5) => 0
(cc 11 4)
(cc -14 4) => 0
(cc 11 3)
(cc 1 3)
(cc -9 3) => 0
(cc 1 2)
(cc -4 2) => 0
(cc 1 1)
(cc 0 1) => 1
(cc 1 0) => 0
(cc 11 2)
(cc 6 2)
(cc 1 2)
(cc -4 2) => 0
(cc 1 1)
(cc 0 1) => 1
(cc 1 0) => 0
(cc 6 1)
(cc 5 1)
(cc 4 1)
(cc 3 1)
(cc 2 1)
(cc 1 1)
(cc 0 1) => 1
(cc 1 0) => 0
(cc 2 0) => 0
(cc 3 0) => 0
(cc 4 0) => 0
(cc 5 0) => 0
(cc 6 0) => 0
(cc 11 1)
(cc 10 1)
(cc 9 1)
(cc 8 1)
(cc 7 1)
(cc 6 1)
(cc 5 1)
(cc 4 1)
(cc 3 1)
(cc 2 1)
(cc 1 1)
(cc 0 1) => 1
(cc 1 0) => 0
(cc 2 0) => 0
(cc 3 0) => 0
(cc 4 0) => 0
(cc 5 0) => 0
(cc 6 0) => 0
(cc 7 0) => 0
(cc 8 0) => 0
(cc 9 0) => 0
(cc 10 0) => 0
(cc 11 0) => 0
Orders of growth: - Steps: \(\Theta(n^5)\) because there are 5 types of coins. - Space: \(\Theta(n)\) because the maximum depth of the tree grows linearly.
Remember: for a tree-recursive process, space is proportional to the maximum depth of the tree, and the number of steps is the number of leaves.