最少硬币数 代码 求注释
#include<iostream> using namespace std;
int V[20];
int n, S;
int minv[200],maxv[200];
int d[200]={0},vis[200] = {0};
int min(int x, int y)
{
return x < y ? x : y;
}
int dp(int S)
{
if(S == 0) return 0;
if(vis[S]) return d[S];
int &ans = d[S];
ans = (1<<30);
for(int i = 0; i < n; i++)
if(S >= V[i])
ans = min(ans, dp(S - V[i]) + 1);
return ans;
}
void print_ans(int *d, int S){
for(int i = 0; i < n; i++)
if(S >= V[i] && d[S] == d[S - V[i]] + 1){
cout << V[i] << ' ';
print_ans(d, S - V[i]);
break;
}
}
int main()
{
minv[0] = maxv[0] = 0;
cout << "输入硬币种数:";
cin >> n;
cout << "依次输入其面值:" << endl;
for(int i = 0; i < n; i++)
cin >> V[i];
cout << "输入要凑的总面值:";
cin >> S;
cout << "最少需要的硬币数为:" << dp(S) << endl << "它们分别是:";
print_ans(d, S);
return 0;
}