题解 | #称砝码#
称砝码
https://www.nowcoder.com/practice/f9a4c19050fc477e9e27eb75f3bfd49c
import java.util.ArrayList; import java.util.List; import java.util.Scanner; import java.util.Set; import java.util.HashSet; // 注意类名必须为 Main public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); // 注意 hasNext 和 hasNextLine 的区别 while (in.hasNextInt()) { // 注意 while 处理多个 case int len = in.nextInt(); int[] weight = new int[len]; int[] nums = new int[len]; for (int i = 0; i < len; i++) { weight[i] = in.nextInt(); } for (int i = 0; i < len; i++) { nums[i] = in.nextInt(); } System.out.println(getWeightNum(weight, nums)); } in.close(); } private static int getWeightNum(int[] weight, int[] nums) { Set<Integer> set = new HashSet<>(); set.add(0); //遍历砝码的种类 for (int i = 0; i < nums.length; i++) { //System.out.println(i + "--------" + set.size()); List<Integer> list = new ArrayList<>(set); //num[i]表示每种砝码的最大数量,可取值就是从0到num[i] for (int j = 0; j <= nums[i]; j++) { //System.out.println(j + "==" + list.size()); //k是当前能测的所有重量+某个砝码从1个到最大值的各种质量放到set去重,就是当前能测得所有质量 for (Integer k : list) { set.add(k + weight[i] * j); //System.out.println(j + "==" + i + "==" + weight[i] + "==" + j); } } } return set.size(); } }