题解 | #称砝码#
称砝码
https://www.nowcoder.com/practice/f9a4c19050fc477e9e27eb75f3bfd49c
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Scanner;
import java.util.Set;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNextLine()) {
String nextLine = in.nextLine();
if (Objects.isNull(nextLine) || nextLine.equals("")) {
break;
}
String nextLine1 = in.nextLine();
String nextLine2 = in.nextLine();
String[] s1 = nextLine1.split(" ");
String[] s2 = nextLine2.split(" ");
// 记录每种砝码的重量
Map<Integer, Integer> weightMap = new HashMap<>();
// 记录每种砝码数量
Map<Integer, Integer> typeCountMap = new HashMap<>();
for (int i = 0; i < s1.length; i++) {
weightMap.put(i, Integer.parseInt(s1[i]));
typeCountMap.put(i, Integer.parseInt(s2[i]));
}
Set<Integer> result = new HashSet<>();
// 先记录什么都不放,记录重量,这一步非常关键。
result.add(0);
int n = Integer.parseInt(nextLine);
// 以下逻辑大意是:不断的往之前已经放好的砝码情景分别添加新的砝码作为的新的场景,
// 并且将砝码的组合转换为用重量来表示不同的场景可以提升计算速度
// 巧妙的利用0的重量的场景,来作为每一种砝码单独放的新情景的前提情景。
// 遍历n种砝码
for (int i = 0; i < n; i++) {
// 取出当前遍历的砝码种类i
// 创建一个集合,保存了上一次set的结果
List<Integer> tempResult = new ArrayList<>(result);
// 遍历当前遍历的砝码的数量
Integer typeCount = typeCountMap.get(i);
for (Integer j = 1; j <= typeCount; j++) {
// 遍历出集合中已经存储的放砝码的情况,并分别放入当前砝码数量后作为新的情况加入的set中
// 当前遍历的砝码种类,数量一个个往上推上去
for (int m = 0; m < tempResult.size(); m++) {
result.add(tempResult.get(m) + j * weightMap.get(i));
}
}
}
System.out.println(result.size());
}
}
}
学而思公司福利 644人发布