题解 | #称砝码#
称砝码
https://www.nowcoder.com/practice/f9a4c19050fc477e9e27eb75f3bfd49c
import java.util.*; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); // 注意 hasNext 和 hasNextLine 的区别 int n = in.nextInt(); in.nextLine(); String[] strings1 = in.nextLine().split(" "); String[] strings2 = in.nextLine().split(" "); int[] m = new int[n];// 每种砝码的重量 int[] x = new int[n];// 每种砝码对应的个数 for (int i = 0; i < strings1.length; i++) { m[i] = Integer.parseInt(strings1[i]); } for (int i = 0; i < strings1.length; i++) { x[i] = Integer.parseInt(strings2[i]); } List<Integer> list = new ArrayList<>(); list.add(0); for (int i = 0; i < m.length; i++) { int weight = m[i]; int num = x[i]; for (int j = 0; j < num; j++) { list.add(weight); } } Set<Integer> set = new HashSet<>(); set.add(0); for (int i = 0; i < list.size(); i++) { int weight = list.get(i); Set<Integer> tmpSet = new HashSet<>(); for (int tmp : set) { tmpSet.add(weight + tmp); } set.addAll(tmpSet); } System.out.println(set.size()); } }