题解 | #称砝码#
称砝码
https://www.nowcoder.com/practice/f9a4c19050fc477e9e27eb75f3bfd49c
import java.util.HashSet; import java.util.Scanner; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int weight[] = new int[n]; int num[] = new int[n]; for (int i = 0; i < n; i++) { weight[i] = in.nextInt(); } for (int i = 0; i < n; i++) { num[i] = in.nextInt(); } HashSet<Integer> set = new HashSet<Integer>(); set.add(0); for (int i = 0; i < n; i++) { for (int j = 0; j < num[i]; j++) { // 增加此砝码与不加的情况(不加则不修改set) HashSet<Integer> addSet = new HashSet<Integer>(); for (Integer k : set) { if (!set.contains(k + weight[i])) { addSet.add(k + weight[i]); } } set.addAll(addSet); } } System.out.println(set.size()); } }
一共N个砝码(n1 + n2 + ..+ nn)
每个砝码可选择加或不加,共2^n种选择
遍历砝码,添加则修改已有重量的set,不加则保持原有set,两个set合一继续遍历