#include<iostream>
#include<cstdio>
#include<cstring>
//本来想用 memset 函数来着,后来除了岔子!除了赋值为 0,赋值为其它就不要用了!
using namespace std;
int sorts, coin[10];//sorts:硬币种类数,coin[]:硬币面值(从小到大)
int target;//目标总值
int ans[30];//ans[i] 表示找到的配成 i 时最少硬币数
int main() {
for (int i = 0;i < 30;i++) ans[i] = 1000;//赋初值(视为无穷大,因为使用的数值较小)
cin >> sorts >> target;
ans[0] = 0;//关键的初始化!!!
for (int i = 0;i < sorts;i++) cin >> coin[i];//规定硬币面值从小到大输入
for (int i = 1;i <= target;i++) {
for (int j = 0;j < sorts;j++) {
if (i >= coin[j] && ans[i - coin[j]] < 1000) {//不可以缺少了判断条件
ans[i] = min(ans[i - coin[j]] + 1, ans[i]);
}
}
}
if (ans[target] == 1000) cout << -1;
else cout << ans[target];
//for(int i=0;i<=target;i++) cout<<ans[i]<<' ';
return 0;
}
测试:
(不多说了,继续研究动态规划思想去!!)