给定N个正整数A1,A2,…,AN,从中选出若干个数,使它们的和为M,求有多少种选择方案。
输入格式
第一行包含两个整数N和M。
第二行包含N个整数,表示A1,A2,…,AN。
输出格式
包含一个整数,表示可选方案数。
数据范围
1≤N≤100,
1≤M≤10000,
1≤Ai≤1000
输入样例:
4 4
1 1 2 2
输出样例:
3
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const int N=110,M=10010;
LL f[N][M];
int a[N];
int main(){
int n,m;
cin>>n>>m;
for(int i=1;i<=n;i++){
cin>>a[i];
}
for(int i=1;i<=n;i++){
f[i][0]=1;//至少有一种
}
for(int i=1;i<=n;i++){
for(int j=0;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];
return 0;
}
//一维优化
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const int N=110,M=10010;
int f[M];
int main(){
int n,m;
cin>>n>>m;
f[0]=1;//至少有一种
for(int i=0;i<n;i++){
int v;
cin>>v;
for(int j=m;j>=v;j--){
f[j]+=f[j-v];
}
}
cout<<f[m];
return 0;
}