这是一道简单的背包问题。
int main() {
//int N = 7;
int a[7] = { 50,80,50,80,200,160,200 };
vector<vector<bool>>dp(500,vector<bool>(10, false));
dp[0][0] = true;
for (int i = 1; i <= 7; i++) {
for (int j = a[i-1]; j < 500; j++) {
dp[j][i] = dp[j][i - 1] || dp[j - a[i-1]][i - 1];
}
}
for (int i = 373; i < 500; i++) {
if (dp[i][7]) {
cout << "最小需要花费"<<i<<"个币"<<endl;
vector<int>res;
int k = i;
for (int j = 7; j > 0; j--) {
if (k <= 0)break;
if (dp[k - a[j - 1]][j - 1]) {
res.push_back(j);
k -= a[j - 1];
}
}
cout << "选择的编号为:" << endl;
for (int j = 0; j < res.size()-1; j++)cout << res[j] << "、";
cout << res[res.size() - 1] << endl;
return 0;
}
}
cout << "null";
return 0;
}
写这个都花了好久,我真是废了。