题解 | #称砝码#

称砝码

http://www.nowcoder.com/practice/f9a4c19050fc477e9e27eb75f3bfd49c

暴力递归:利用set去重,递归加上砝码重量即可。

public class Main {
    static Set<Integer> set = new HashSet<>();
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNextInt()) { // 注意 while 处理多个 case
            int n = in.nextInt();
            int m[] =new int[n];
            int x[] = new int[n];
            for(int i =0;i<n;++i){
                m[i] = in.nextInt();
            }
            for(int i =0;i<n;++i){
                x[i] = in.nextInt();
            }
            func(m,x,0,0);
            System.out.println(set.size());
        }
    }
    public static void func(int[] m ,int[]x,int index,int weight){
        if(index==x.length){
            return ;
        }
        if(!set.contains(weight))set.add(weight);
        if(x[index]>0){
             x[index]--;
             func(m,x,index,weight+m[index]);
             x[index]++;
        }
        func(m,x,index+1,weight);
    }
}
全部评论

相关推荐

点赞 评论 收藏
分享
双尔:你就写拥有ai开发经历,熟练运用提示词,优化ai,提高ai回答质量
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务