题解 | 称砝码

称砝码

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

import java.util.*;

//根据题目获取数据n,weights,numbers
//合并weights和numbers数组为一个数组method,如2个1g的和1个2g的砝码则记录成[1,1,2]
//根据数组method,可以使用迭代法,回溯法,位运算法 得到method数组的所有组合(子集)
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int[] weights = new int[n];
        int[] numbers = new int[n];
        for (int i = 0; i < n; i++) {
            weights[i] = in.nextInt();
        }
        for (int i = 0; i < n; i++) {
            numbers[i] = in.nextInt();
        }
        List<Integer> method=new ArrayList<>();
        method.add(0);
        //将两个数组合并成1个数组,如2个1g的和1个2g的砝码则记录成[1,1,2]
        for(int i=0;i<weights.length;i++){
            int j=0;
            while(j<numbers[i]){
                method.add(weights[i]);
                j++;
            }

        }
        //将method 生成所有的组合,这里使用迭代法
        Set<Integer> res =new LinkedHashSet<>();
        res.add(0);
        for(int i=0;i<method.size();i++){
            List<Integer> tempList = new ArrayList<Integer>();
            for(Integer item:res){
                tempList.add(item+method.get(i));
            }
            res.addAll(tempList);
            tempList.clear();
        }
        
        System.out.println(res.size());




    }
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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