贪心算法 顾名思义:把当前所有的可能都列举出来。
#include <iostream>
#include <stdio.h>
using namespace std;
#define N 7
int value[N] = { 1,2,5,10,20,50,100 };
int number[N] = { 10,2,3,1,2,3,5 };
/*对输入的零钱数,找到至少要用的纸币的数量
参数:
money - 要找的零钱数
返回:
至少要用的纸币数量,-1表示找不开
*/
int solve(int money)
{
int num = 0;
int i = 0;
for (i = N - 1; i >= 0; i--)
{
int j = money / value[i];
int c = j > number[i] ? number[i] : j;
cout << "需要用面值 " << value[i] << " 的纸币 " << c << " 张" << endl;
money -= c * value[i];
num += c;
if (money == 0) break;
}
if (money > 0) num = -1;
return num;
}
int main()
{
int money = 0;
int num = 0;
cout << "请输入要找零的数目:" << endl;
cin >> money;
num = solve(money);
if (num == -1)
{
cout << "对不起,零钱不够,找不开!" << endl;
}
else
{
cout << "成功的使用至少 " << num << " 张纸币实现找零/支付" << endl;
}
system("pause");
return 0;
}