给一个正整数序列,再给一个t值,求其中和为t的子集的个数
#include<iostream>
#include<map>
using namespace std;
const int N = 10010, M = 20;
int n, m;
int a[N];
int f[N][M];
int main(){
cin >> n >> m;
for(int i = 1; i <= n; i ++) cin >> a[i];
f[0][0] = 1;
for(int i = 1; i <= n; i ++)
for(int j = 0; j <= m; j ++)
f[i][j] = f[i - 1][j] + f[i - 1][j - a[i]];
cout << f[n][m] << endl;
return 0;
}
空间优化
#include<iostream>
#include<map>
using namespace std;
const int N = 10010, M = 20;
int n, m;
int a[N];
int f[M];
int main(){
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 >= 0; j --)
f[j] = f[j] + f[j - a[i]];
cout << f[m] << endl;
return 0;
}