题解 | #称砝码#

称砝码

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

import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNextLine()) { // 注意 while 处理多个 case
            int n = Integer.parseInt(in.nextLine());
            String[] mn = in.nextLine().split(" ");
            String[] xn = in.nextLine().split(" ");
            HashSet<Integer> haset=new HashSet<Integer>();
            haset.add(0);
            for(int i=0;i<n;i++){//第一个循环为每一次讨论一种砝码而立
                ArrayList<Integer> list=new ArrayList<>(haset);//ArrayList和HashSet都是继承Collection接口,所以这里可以这么初始化,原理是每一次对上一次的所有结果进行砝码的添加
                for(int j=1;j<=Integer.parseInt(xn[i]);j++){
                    for(int k=0;k<list.size();k++){
                        haset.add(list.get(k)+j*Integer.parseInt(mn[i]));
                    }
                }
            }
            System.out.println(haset.size());
            


        }
    }
}

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务