题解 | #称砝码#

称砝码

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);
        //数据提取
        int kind = in.nextInt();
        int[] weight = new int[kind];
        int[] number = new int[kind];
        for(int i=0; i<kind; i++){
            weight[i] = in.nextInt();
        }
        for(int i=0; i<kind; i++){
            number[i] = in.nextInt();
        }
        //申请两个hashset,一个存储最终的,一个存储每一种的临时的
        HashSet<Integer> hashSet = new HashSet<Integer>();
        hashSet.add(0);
        //对每一种砝码遍历
        for(int i=0; i<kind; i++){
            //每一种砝码创建一个hashSetTemp
            HashSet<Integer> hashSetTemp = new HashSet<Integer>();
            //根据数量列举出 当前种类 所有可能
            for(int j=1; j<=number[i]; j++){
                for(Integer oldWeight : hashSet){
                    hashSetTemp.add(weight[i] * j + oldWeight);
                }
                //将本次结果存入hashSet,以便后续的种类可以影响到完整的hashSet
            }
            hashSet.addAll(hashSetTemp);
        }
        //输出结果
        System.out.print(hashSet.size());

    }
}

全部评论

相关推荐

点赞 评论 收藏
分享
06-28 22:48
已编辑
广东金融学院 Java
小浪_Coding:学院本+这俩项目不是buff叠满了嘛
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

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