SICP 实例 ExchangeMoney
(define (first-denomination kinds-of-coin)
(cond ((= kinds-of-coin 1) 1)
((= kinds-of-coin 2) 5)
((= kinds-of-coin 3) 10)
((= kinds-of-coin 4) 25)
((= kinds-of-coin 5) 50)))
(define (cc amount kinds-of-coin)
(cond ((= amount 0) 1)
((or (< amount 0) (= kinds-of-coin 0)) 0)
(else (+ (cc amount
(- kinds-of-coin 1))
(cc (- amount
(first-denomination kinds-of-coin))
kinds-of-coin)))))
(define (count-change amount)
(cc amount 5))
(count-change 100)
Java实现:
/**
* Created by Ramble on 2017/11/22.
*/
public class ExchangeMoney {
public static int first_denomination(int kinds_of_coin) {
switch (kinds_of_coin) {
case 1: {
return 1;
}
case 2: {
return 5;
}
case 3: {
return 10;
}
case 4: {
return 25;
}
case 5: {
return 50;
}
default:
return 0;
}
}
public static int cc(int amount, int kinds_of_coin) {
if (amount==0) {
return 1;
} else if (amount<0||kinds_of_coin==0) {
return 0;
} else {
return cc(amount, kinds_of_coin-1) + cc(amount - first_denomination(kinds_of_coin), kinds_of_coin);
}
}
public static int count_change(int amount) {
return cc(amount, 5);
}
public static void main(String[] args) {
long startTime = System.currentTimeMillis();
System.out.println(count_change(1000));
long endTime = System.currentTimeMillis();
System.out.println("程序运行时间:"+(endTime-startTime)+"ms");
}
}