找零 递归 打印所有结果

来源:互联网 发布:博彦科技面试题java 编辑:程序博客网 时间:2024/06/07 01:07

题目:现有1元、2元、5元、10元、20元面值不等的钞票,问需要20元钱有多少种找钱方案,打印所有的结果!

 

分析:此题如果没要求打印结果,只要求打印出一共有多少种方案,那么可以直接用动态规划,参考背包问题——“01背包”及“完全背包”装满背包的方案总数分析及实现

如果要求打印所有结果,那递归是再好不过的了。

 

[html] view plaincopy
  1. #include <iostream>  
  2. #include <string.h>  
  3. using namespace std;  
  4.   
  5. //20块钱找零,零钱由1、2、5、10四种币值  
  6. #define MAX_VALUE   20  
  7.   
  8. int array[] = {1,2,5,10,MAX_VALUE};  
  9. int next[MAX_VALUE] = {0};  
  10.   
  11. void SegNum(int nSum, int* pData, int nDepth)  
  12. {  
  13.     if(nSum < 0)  
  14.         return;  
  15.   
  16.     if(nSum == 0)  
  17.     {  
  18.         for(int j = 0; j < nDepth; j++)  
  19.             cout << pData[j] << " ";  
  20.         cout << endl;  
  21.   
  22.         return;  
  23.     }  
  24.   
  25.     int i = (nDepth == 0 ? next[0] : pData[nDepth-1]);  
  26.     for(; i <= nSum;)  
  27.     {  
  28.         pData[nDepth++] = i;  
  29.         SegNum(nSum-i,pData,nDepth);  
  30.         nDepth--;  
  31.   
  32.         i = next[i];  
  33.     }  
  34. }  
  35.   
  36. void ShowResult(int array[],int nLen)  
  37. {  
  38.     next[0] = array[0];  
  39.     int i = 0;  
  40.     for(; i < nLen-1; i++)  
  41.         next[array[i]] = array[i+1];  
  42.     next[array[i]] = array[i]+1;  
  43.   
  44.     int* pData = new int [MAX_VALUE];  
  45.     SegNum(MAX_VALUE,pData,0);  
  46.     delete [] pData;  
  47. }  


测试代码如下

[cpp] view plaincopy
  1. int main()  
  2. {  
  3.     //找零钱测试  
  4.     ShowResult(array,sizeof(array)/sizeof(int));  
  5.   
  6.     system("pause");  
  7.     return 0;  
  8. }  
0 0