2015华为机试练习之找零钱
题目描述:
我们知道人民币有1、2、5、10、20、50、100这几种面值。现在给你n(1≤n≤250)元,让你计算换成用上面这些面额表示且总数不超过100张,共有几种。比如4元,能用4张1元、2张1元和1张2元、2张2元,三种表示方法。
输入:输入有多组,每组一行,为一个整合n。输入以0结束。
输出:输出该面额有几种表示方法。
样例输入:
1
4
0
样例输出:
1
3
代码如下:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int money[] = { 1, 2, 5, 10, 20, 50, 100 };
void dfs(int n, vector<vector<int>>&res, vector<int>&path)
{
if (n < 0)return;
if (n==0)
{
vector<int> tmp = path;
sort(tmp.begin(), tmp.end());
if (find(res.begin(), res.end(), tmp)==res.end())
{
res.push_back(path);
}
return;
}
for (int i = 0; i < 7; i++)
{
if (n-money[i]>=0)
{
path.push_back(money[i]);
dfs(n - money[i], res, path);
path.pop_back();
}
}
}
int getCount(int n)
{
vector<vector<int>>res;
vector<int> path;
dfs(n, res, path);
return res.size();
}
int main()
{
int n;
while (cin>>n)
{
cout << getCount(n) << endl;
}
return 0;
}