题解 | 称砝码
称砝码
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()); } } }