题解 | 称砝码

称砝码

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());
        }
    }
}

全部评论

相关推荐

05-22 09:23
门头沟学院 Java
点赞 评论 收藏
分享
07-01 13:37
门头沟学院 Java
steelhead:不是你的问题,这是社会的问题。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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