[转]找零钱递归实现
题目:现有1元、2元、5元、10元、20元面值不等的钞票,问需要20元钱有多少种找钱方案,打印所有的结果!
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 }
测试代码:
int main()
{
//找零钱测试
ShowResult(array,sizeof(array)/sizeof(int));
system("pause");
return 0;
}
这个问题的一个变种是求一个整数的所有和式的组合,将本题中的面值扩展为1元、2元、3元....20元,就可以了。

浙公网安备 33010602011771号