题解 | #称砝码#

称砝码

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

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Scanner;
import java.util.Set;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNextLine()) {
            String nextLine = in.nextLine();
            if (Objects.isNull(nextLine) || nextLine.equals("")) {
                break;
            }
            String nextLine1 = in.nextLine();
            String nextLine2 = in.nextLine();
            String[] s1 = nextLine1.split(" ");
            String[] s2 = nextLine2.split(" ");
            // 记录每种砝码的重量
            Map<Integer, Integer> weightMap = new HashMap<>();
            // 记录每种砝码数量
            Map<Integer, Integer> typeCountMap = new HashMap<>();
            for (int i = 0; i < s1.length; i++) {
                weightMap.put(i, Integer.parseInt(s1[i]));
                typeCountMap.put(i, Integer.parseInt(s2[i]));
            }
            Set<Integer> result = new HashSet<>();

            // 先记录什么都不放,记录重量,这一步非常关键。
            result.add(0);

            int n = Integer.parseInt(nextLine);
            // 以下逻辑大意是:不断的往之前已经放好的砝码情景分别添加新的砝码作为的新的场景,
            // 并且将砝码的组合转换为用重量来表示不同的场景可以提升计算速度
            // 巧妙的利用0的重量的场景,来作为每一种砝码单独放的新情景的前提情景。

            // 遍历n种砝码
            for (int i = 0; i < n; i++) {
                // 取出当前遍历的砝码种类i
                // 创建一个集合,保存了上一次set的结果
                List<Integer> tempResult = new ArrayList<>(result);
                // 遍历当前遍历的砝码的数量
                Integer typeCount = typeCountMap.get(i);
                for (Integer j = 1; j <= typeCount; j++) {
                    // 遍历出集合中已经存储的放砝码的情况,并分别放入当前砝码数量后作为新的情况加入的set中
                    // 当前遍历的砝码种类,数量一个个往上推上去
                    for (int m = 0; m < tempResult.size(); m++) {
                        result.add(tempResult.get(m) + j * weightMap.get(i));
                    }
                }
            }
            System.out.println(result.size());
        }

    }

}

全部评论

相关推荐

不愿透露姓名的神秘牛友
10-09 16:39
已编辑
英俊的靓仔offer...:我感觉吧第二个寻迹小车的项目有点配不上你的学历了,写上去扣分了都可能对你来说,好歹是211硕士嘛,写在我这种二本混子的简历上还说得过去,个人观点哦,能再有个好点的项目应该会好很多,或者干脆不写第二个换个啥实习经历?
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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