題目:
小蒜有 n(1≤n≤20)n(1 \le n \le 20)n(1≤n≤20) 個正整數,找出其中和爲 t(tt(tt(t 也是正整數)的可能的組合方式。如:
n=5,5n=5,5n=5,5 個數分別爲 1,2,3,4,51,2,3,4,51,2,3,4,5,t=5t=5t=5;
那麼可能的組合有 5=1+45=1+45=1+4 和 5=2+35=2+35=2+3 和 5=55=55=5 三種組合方式。
輸入格式
輸入的第一行是兩個正整數 nnn 和 ttt,用空格隔開,其中 1≤n≤201 \le n \le 201≤n≤20, 表示正整數的個數,ttt 爲要
求的和 (1≤t≤1000)(1 \le t \le 1000)(1≤t≤1000)
接下來的一行是 nnn 個正整數,用空格隔開。
輸出格式
和爲 ttt 的不同的組合方式的數目。
輸出時每行末尾的多餘空格,不影響答案正確性
樣例輸入
5 5
1 2 3 4 5
樣例輸出
3
解題思路:這個題就是動態規劃,輸入n個數,看看能有多少種方式讓這n個數組合成和爲t。也就是要求dp[t]的種數可以先求dp[ t-a[i] ]…
程序代碼:
#include<iostream>
#include<algorithm>
#include<string.h>
using namespace std;
int main()
{
int a[1000],f[10010];
int i,j,t,m,n;
while(scanf("%d%d",&n,&t)!=EOF)
{
memset(f,0,sizeof(f));
f[0]=1;//f[0]只有0一種方式
for(i=1;i<=n;i++)
scanf("%d",&a[i]);
for(i=1;i<=n;i++)
for(j=t;j>=a[i];j--)
f[j]+=f[j-a[i]];
printf("%d\n",f[t]);
}
return 0;
}