【牛客】神奇的口袋

链接:https://www.nowcoder.com/questionTerminal/9aaea0b82623466a8b29a9f1a00b5d35

 

有一个神奇的口袋,总的容积是40,用这个口袋可以变出一些物品,这些物品的总体积必须是40。John现在有n个想要得到的物品,每个物品的体积分别是a1,a2……an。John可以从这些物品中选择一些,如果选出的物体的总体积是40,那么利用这个神奇的口袋,John就可以得到这些物品。现在的问题是,John有多少种不同的选择物品的方式。

输入描述:

输入的第一行是正整数n (1 <= n <= 20),表示不同的物品的数目。接下来的n行,每行有一个1到40之间的正整数,分别给出a1,a2……an的值。


 

输出描述:

输出不同的选择物品的方式的数目。

示例1

输入

3
20
20
20

输出

3

【解题思路】: 采用递归思想: ①物品n个,物品体积逐一放入weight[]中 ②递归函数count(int s,int n) : 其 中s为剩余物品重量,n为剩余可选的物品个数
则分以下两步递归求解:
a.从后往前装,装上weight[n]后,若剩余物品仍然有解 则count(s-weight[n],n-1);
b.若装了weight[n]后,无解,则删除该包,尝试第n-1个 count(s,n-1);
 

import java.util.*;
public class Main{
    static int []weight;
    static int count = 0;
    static int n;
    public static void main(String []args){
        Scanner sc = new Scanner(System.in);
        while(sc.hasNext()){
             n = sc.nextInt();
            weight = new int[n+1];
            for(int i = 1;i<weight.length;i++){
                weight[i] = sc.nextInt();
            }
        }
        count(40,n);
        System.out.println(count);
    }
    public static void count(int s,int n){
        if(s == 0){
            count++;
            return;
        }
        if(s<0 || n<1)
            return;
        count(s-weight[n],n-1);
        count(s,n-1);
    }
}
发布了139 篇原创文章 · 获赞 93 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/weixin_43271086/article/details/105343607