题解 | 称砝码

称砝码

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

import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        while(scanner.hasNextLine()) {
            String typeLine = scanner.nextLine();
            String weightLine = scanner.nextLine();
            String numLine = scanner.nextLine();
            String[] weights = weightLine.split("\\s");
            String[] nums = numLine.split("\\s");
            HashSet<Integer> weightHashSet = new HashSet<>();
            weightHashSet.add(0);
            for(int i = 0; i < weights.length; i ++)
            {
                int weight = Integer.parseInt(weights[i]);
                int num = Integer.parseInt(nums[i]);
                /**
                 * 请注意wtList变量的位置,是在for(int j = 1; j <= num; j ++)循环外
                 * 请注意,不能直接对weightHashSet直接进行迭代,会发生并发修改错误
                 */
                List<Integer> wtList = new ArrayList<>(weightHashSet);
                for(int j = 1; j <= num; j ++)
                {
                    /**
                     * 不要这样写weight = weight * j;,全部累加到变量weight里了
                     */
                    int newWeight = weight * j;

                    for(int k = 0; k < wtList.size(); k ++)
                    {
                        Integer wt = wtList.get(k);
                        weightHashSet.add(wt + newWeight);
                    }
                }
            }
            System.out.println(weightHashSet.size());
        }
    }
}

全部评论

相关推荐

码农索隆:7*24,随时待命,这是去🇷🇺打仗去了啊
点赞 评论 收藏
分享
仁者伍敌:牛子这些人还会点一个自动回复,boss都不带回复的
点赞 评论 收藏
分享
陈逸轩1205:才105 哥们在养生呢
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-11 17:10
什么素质,我请问呢,要掉小珍珠了。。。又憋屈又生气
Steven267:这不喷回去?花钱是大爷,记住这个道理
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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