题目描述
有一个神奇的口袋,总的容积是40,用这个口袋可以变出一些物品,这些物品的总体积必须是40。John现在有n个想要得到的物品,每个物品的体积分别是a1,a2……an。John可以从这些物品中选择一些,如果选出的物体的总体积是40,那么利用这个神奇的口袋,John就可以得到这些物品。现在的问题是,John有多少种不同的选择物品的方式。
输入
输入的第一行是正整数n (1 <= n <= 20),表示不同的物品的数目。接下来的n行,每行有一个1到40之间的正整数,分别给出a1,a2……an的值。
输出
输出不同的选择物品的方式的数目。
样例输入
2
12
28
3
21
10
5
样例输出
1
0
代码
#include<cstdio>
const int maxn = 20;
int totalV = 40;
int item[maxn],cnt = 0,v = 0;
void calculateV(int index,int n) {
if(v == totalV) {
cnt++;
return;
} else if(v > totalV) {
return;
}
if(index == n){
return;
}
for(int i = index; i < n; i++) {
v += item[i];
calculateV(i + 1, n);
v -= item[i];
}
}
int main() {
int n;
while(scanf("%d",&n)!=EOF) {
for(int i=0;i<n;i++) {
scanf("%d",&item[i]);
}
cnt = 0;
calculateV(0,n);
printf("%d\n",cnt);
}
return 0;
}
后记
这道题自己绕的很晕,还是不怎么会写递归。