子集の子集题解
1. 题意概括
个硬币,每个价值 。对于所有能够凑出 的硬币集合,其子集能表示的价值有多少种?
2. 思路分析
我们可以用 dp 来解决这道题。
3. AC 代码
#include <bits/stdc++.h>
#define int long long
using namespace std;
int a[502];
bool dp[502][502][502];
vector<int> ans;
signed main() {
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int n, k;
cin >> n >> k;
for (int i = 1; i <= n; i++) {
cin >> a[i];
}
dp[0][0][0] = 1;
for (int i = 0; i < n; i++) {
for (int j = 0; j <= k; j++) {
for (int l = 0; l <= k; l++) {
dp[i + 1][j][l] |= dp[i][j][l];
if (j + a[i + 1] <= k) {
dp[i + 1][j + a[i + 1]][l] |= dp[i][j][l];
}
if (l + a[i + 1] <= k) {
dp[i + 1][j][l + a[i + 1]] |= dp[i][j][l];
}
}
}
}
for (int i = 0; i <= k; i++) {
if (dp[n][i][k - i]) {
ans.push_back(i);
}
}
cout << ans.size() << endl;
for (auto i : ans) {
cout << i << " ";
}
return 0;
}