不限数目的1、5、10、20、50面额的纸币,有多少种方法凑出100元

1,有不限数目的1、5、10、20、50面额的纸币,有多少种方法凑出100元

解答:实质就是暴力枚举

#include
#include
using namespace std;

const int Len = 5;
int ans = 0;
int m[Len] = {50, 20, 10, 5, 1};
int total[Len] = {2, 5, 10, 20, 100};
int n[Len];
int sum = 100;

void GetNum(int m[], int n[])
{
while (true)
{
int rel = 0;
for (int i = 0; i < 5; i++)
rel += m[i] * n[i];
if (rel == sum)
{
ans++;
for (int i = 0; i < Len; i++)
cout << n[i] << " ";
cout << endl;
}

int k = Len - 1;
while (k >= 0)
{
if (n[k] < total[k])
{
n[k]++;
break;
}
else
{
n[k] = 0;
k--;
}
}
if (k < 0)
break;
}

}

void RecursiveGetNum(int m[], int n[], int index)
{
if (index == Len)
{
int rel = 0;
for (int i = 0; i < Len; i++)
rel += m[i] * n[i];
if (rel == sum)
{
ans++;
for (int i = 0; i < Len; i++)
cout << n[i] << " ";
cout << endl;
}
return;
}
for (n[index] = 0; n[index] <= total[index]; n[index]++)
{
RecursiveGetNum(m, n, index + 1);
}

}

int main()
{
GetNum(m, n);
//RecursiveGetNum(m, n, 0);
cout << ans << endl;
return 0;
}

你可能感兴趣的:(算法题目)