题解 | #称砝码#

称砝码

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


public class Main {
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        while(sc.hasNext()){
            int n = sc.nextInt();
            int[] sMs = new int[n];
            int[] sXs = new int[n];
            HashSet<Integer> set = new HashSet<>();
            //关键点就是set必须手动添加一个元素,从而进入循环,添加元素。
            set.add(0);
            // 砝码种类
            for (int i = 0; i < n; i++) {
                sMs[i] = sc.nextInt();
            }
            // 砝码个数
            for (int i = 0; i < n; i++) {
                sXs[i] = sc.nextInt();
            }
            for (int i = 0; i < n; i++) {
                ArrayList<Integer> list = new ArrayList<>(set);
                //每个砝码的个数,关键步骤,只要有砝码,至少为1个
                for (int j = 1; j <= sXs[i]; j++) {
                    for (int k = 0; k < list.size(); k++) {
                        set.add(list.get(k) + sMs[i] * j);
                    }
                }
            }
            System.out.println(set.size());
        }
    }
}
全部评论
//关键点就是set必须手动添加一个元素,从而进入循环,添加元素。 set.add(0); 对手动加一个元素,正好0是一种结果集,所以把0加进去。
2 回复 分享
发布于 2022-04-03 09:17
看了那么多复杂的答案根本不想再看下去,还是你的最简洁
点赞 回复 分享
发布于 2022-06-16 15:39

相关推荐

ResourceUt...:楼主有自己的垃圾箱,公司也有自己的人才库
点赞 评论 收藏
分享
评论
10
15
分享

创作者周榜

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