解题思路
代码
原始做法
#include <iostream>
using namespace std;
const int N = 10010, M = 110;
int f[N][N], a[M];
int main() {
int n, m;
cin >> n >> m;
for (int i = 1; i <= n; i++) cin >> a[i];
f[0][0] = 1;
for (int i = 1; i <= n; i++) {
f[i][0] = 1;
for (int j = 1; j <= m; j++) {
f[i][j] = f[i - 1][j];
if (j >= a[i]) f[i][j] += f[i - 1][j - a[i]];
}
}
cout << f[n][m] << endl;
return 0;
}
优化空间
#include <iostream>
using namespace std;
const int N = 10010, M = 110;
int f[N], a[M];
int main() {
int n, m;
cin >> n >> m;
for (int i = 1; i <= n; i++) cin >> a[i];
f[0] = 1;
for (int i = 1; i <= n; i++) {
for (int j = m; j >= a[i]; j--) f[j] += f[j - a[i]];
}
cout << f[m] << endl;
return 0;
}