题目:现有1元、2元、5元、10元、20元面值不等的钞票,问需要20元钱有多少种找钱方案,打印所有的结果!
分析:此题如果没要求打印结果,只要求打印出一共有多少种方案,那么可以直接用动态规划,参考背包问题——“01背包”及“完全背包”装满背包的方案总数分析及实现
如果要求打印所有结果,那递归是再好不过的了。
- #include <iostream>
- #include <string.h>
- using namespace std;
- //20块钱找零,零钱由1、2、5、10四种币值
- #define MAX_VALUE 20
- int array[] = {1,2,5,10,MAX_VALUE};
- int next[MAX_VALUE] = {0};
- void SegNum(int nSum, int* pData, int nDepth)
- {
- if(nSum < 0)
- return;
- if(nSum == 0)
- {
- for(int j = 0; j < nDepth; j++)
- cout << pData[j] << " ";
- cout << endl;
- return;
- }
- int i = (nDepth == 0 ? next[0] : pData[nDepth-1]);
- for(; i <= nSum;)
- {
- pData[nDepth++] = i;
- SegNum(nSum-i,pData,nDepth);
- nDepth--;
- i = next[i];
- }
- }
- void ShowResult(int array[],int nLen)
- {
- next[0] = array[0];
- int i = 0;
- for(; i < nLen-1; i++)
- next[array[i]] = array[i+1];
- next[array[i]] = array[i]+1;
- int* pData = new int [MAX_VALUE];
- SegNum(MAX_VALUE,pData,0);
- delete [] pData;
- }
测试代码如下
- int main()
- {
- //找零钱测试
- ShowResult(array,sizeof(array)/sizeof(int));
- system("pause");
- return 0;
- }