题解 | #称砝码#
称砝码
https://www.nowcoder.com/practice/f9a4c19050fc477e9e27eb75f3bfd49c
import java.util.*; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); while (in.hasNext()) { int N = Integer.parseInt(in.nextLine()); String[] weight = in.nextLine().split(" "); String[] ma = in.nextLine().split(" "); Map<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < N; i++) { map.put(Integer.parseInt(weight[i]), Integer.parseInt(ma[i])); } Map<Integer, Integer> res = new HashMap<>(); res.put(0, 1); for (int b : map.keySet()) { for (int i = 0; i < map.get(b); i++) { Set<Integer> set = res.keySet(); // 存入新的集合中 Set<Integer> newSet = new HashSet<>(set);//将key保存到新的set,否则put之后会越界 for (int c : newSet) { res.put(c + b, 1); } } } System.out.println(res.size()); } } }