题目描述:
用1元,2元,5元,10元,20元和50元的纸币组成100元,共有多少种情况。
要求输出总方案数和每种方案中各纸币的个数。
4562种
代码:
背包解法:
#include <iostream>
using namespace std;
#define N 6
int w[N];
int number_used[N];
//bool is_used[N];
int countnum=0;
void init()
{
w[0] = 1;
w[1] = 2;
w[2] = 5;
w[3] = 10;
w[4] = 20;
w[5] = 50;
for (int i = 0; i < N; i++)
{
number_used[i] = 0;
}
}
void test(int start_index, int left_weight)
{
if (left_weight == 0)
{
for (int i = 0; i < N; i++)
{
if (number_used[i] > 0) cout << w[i] << "元: "<< number_used[i] <<"张 ";
}
cout << endl;
countnum++;
}
for (int i = start_index; i < N; i++)
{
if (left_weight >= w[i])
{
number_used[i]++;
test(i, left_weight - w[i]);
number_used[i]--;
}
}
}
int main()
{
init();
test(0, 100);
cout<<countnum<<endl;
system("pause");
return 0;
}
另外一种递归求总数解法:
const int v[6] = {1,2,5,10,20,50};
int f(int n, int w)
{
if(n<0) return 0;
if(n==0) return 1;
if(w<0) return 0;
return f(n, w-1) + f(n-v[w], w);
}
void main()
{
cout<<f(100,5)<<endl;
system("pause");
}