标签:style blog color os io for 问题 div
此问题的递归方法很简单,类似于背包的思想。
1 #lang racket 2 (define (count-change amount kinds-of-coins) 3 ( cond ((= amount 0) 1) 4 ((or (< amount 0) (= kinds-of-coins 0))0) 5 (else 6 (+(count-change amount (- kinds-of-coins 1)) (count-change (- amount (some-coin kinds-of-coins)) kinds-of-coins )) ) ) ) 7 8 (define (some-coin kinds-of-coins) 9 ( cond ((= kinds-of-coins 1) 1) 10 ((= kinds-of-coins 2) 5) 11 ((= kinds-of-coins 3) 10) 12 ((= kinds-of-coins 4) 25) 13 ((= kinds-of-coins 5) 50))) 14 15 (count-change 45 5)
1 //cpp 2 #include <iostream> 3 #include <vector> 4 using namespace std; 5 6 int main () 7 { 8 int amount = 55; 9 const int kind_of_coins = 5 ; 10 int coin [ kind_of_coins] = { 1 , 5 , 10, 25 , 50 }; 11 vector< int > result ( amount + 1 , 0 ); 12 result [0 ] = 1; 13 14 for (int i = 0 ; i < kind_of_coins; ++ i ){ 15 int j = coin[ i ]; 16 for (; j <= amount; ++ j ) 17 result [j ] += result[ j - coin [ i]]; 18 } 19 20 cout << result [amount ] << endl; 21 system ("pause" ); 22 23 } 24
1 //cpp 2 #include <iostream> 3 #include <vector> 4 using namespace std; 5 6 int main () 7 { 8 int amount = 55; 9 const int kind_of_coins = 5 ; 10 int coin [ kind_of_coins] = { 1 , 5 , 10, 25 , 50 }; 11 vector< int > result ( amount + 1 , 0 ); 12 result [0 ] = 1; 13 14 for (int i = 0 ; i < kind_of_coins; ++ i ){ 15 int j = coin[ i ]; 16 for (; j <= amount; ++ j ) 17 result [j ] += result[ j - coin [ i]]; 18 } 19 20 cout << result [amount ] << endl; 21 system ("pause" ); 22 23 }
#lang racket
递归版本
(define (fibonacci n)
(cond( (= n 0) 0)
( (= n 1) 1)
(else (+ (fibonacci (- n 1)) (fibonacci (- n 2))))))
迭代版本
#lang racket
(define (fibonacci n)
(fib 0 1 n))
(define (fib first-number second-number n)
(if (= n 0)
first-number
(fib second-number (+ first-number second-number) (- n 1) )))
SICP 找零钱问题背后的思考,布布扣,bubuko.com
标签:style blog color os io for 问题 div
原文地址:http://www.cnblogs.com/gaoduan/p/3909880.html