不同钱币组合方案问题

不同钱币组合方案问题

       Given an infinite number of quarters(25 cents),dimes(10 cents),nickle(5 cents) and pennies(1 cent), 

write code to calculate the number of ways of representing n cents.

基本思想:考虑25cents 10cents  5cents 1cents 个数构成的解空间

代码实现1:

[cpp]  view plain copy
  1. int counts_1(int n)  
  2. {  
  3.     if(n <= 0) return 0;  
  4.     const int units = 4;  
  5.     int nUnit[units] = {25,10,5,1};  
  6.     return recursive(n,0,0,nUnit,units);  
  7. }  
  8.   
  9. int recursive(int n, int curSum, int level, int *pUnit, int units)  
  10. {  
  11.     int cnts = 0;  
  12.     if(level <= units)  
  13.     {  
  14.         if(curSum == n)  
  15.         {  
  16.             cnts = 1;  
  17.         }  
  18.         else  
  19.         {     
  20.             for(int i = 0; i*pUnit[level] <= n-curSum; ++i)  
  21.             {  
  22.                 cnts += recursive(n,curSum+i*pUnit[level],level+1,pUnit,units);  
  23.             }  
  24.         }  
  25.     }  
  26.     return cnts;  
  27. }  

代码实现2(实现思想同上)

[cpp]  view plain copy
  1. //实现代码2  
  2. int counts_2(int n)  
  3. {  
  4.     if(n <= 0) return 0;  
  5.     return makeChange(n,25);  
  6. }  
  7.   
  8. int makeChange(int n, int denom)  
  9. {  
  10.     int next_denom = 0;  
  11.     switch(denom)  
  12.     {  
  13.     case 25:  
  14.         next_denom = 10;  
  15.         break;  
  16.     case 10:  
  17.         next_denom = 5;  
  18.         break;  
  19.     case 5:  
  20.         next_denom = 1;  
  21.         break;  
  22.     case 1:  
  23.         return 1;  
  24.     }  
  25.     int ways = 0;  
  26.     for(int i = 0; i*denom <= n; ++i)  
  27.     {  
  28.         ways += makeChange(n-i*denom,next_denom);  
  29.     }  
  30.     return ways;  
  31. }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值