题目描述:链接:https://www.nowcoder.com/questionTerminal/9aaea0b82623466a8b29a9f1a00b5d35
来源:牛客网
有一个神奇的口袋,总的容积是40,用这个口袋可以变出一些物品,这些物品的总体积必须是40。John现在有n个想要得到的物品,每个物品的体积分别是a1,a2……an。John可以从这些物品中选择一些,如果选出的物体的总体积是40,那么利用这个神奇的口袋,John就可以得到这些物品。现在的问题是,John有多少种不同的选择物品的方式。
解题思路:采用递归思想:①物品n个,物品逐一放入weight[]中②递归函数count(int s,int n);其中s为剩余物品重量,n为可选的物品个数。分为以下两步递归求解:a.从后往前装,装上weight[n]后,若剩余物品仍然有解,则count(s-weigth[n],n-1);b.若装了weight[n]后,无解,则删除该包,尝试第n-1个。count(s,n-1)
代码示例:
static int count=0;
private static void select(int[] array,int sum,int n) {
if(sum==0){
count++;
return;
}
if((sum<0)||((sum>0)&&(n<1))){
return ;
}
select(array,sum-array[n],n-1);
select(array,sum,n-1);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
int n=sc.nextInt();
int i;
int[] array = new int[n+1];
for( i=1;i<=n;i++){
array[i]=sc.nextInt();
}
select(array,40,n);
System.out.println(count);
}
}