题解 | #称砝码#
称砝码
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 的区别
while (in.hasNextInt()) { // 注意 while 处理多个 case
int num = in.nextInt();
int[] typeHeight = new int[num];
int[] numHeight = new int[num];
for (int i = 0; i < num; i++) {
typeHeight[i] = in.nextInt();
}
for (int i = 0; i < num; i++) {
numHeight[i] = in.nextInt();
}
HashSet<Integer> hashSet = new HashSet<>();
hashSet.add(0);
//遍历所有砝码
for (int i = 0; i < num; i++) {
//得到每种砝码的重量和数量
int weight = typeHeight[i];
int number = numHeight[i];
HashSet<Integer> temp = new HashSet<>();
for (int j = 1; j <= number; j++) {
//将当前同种类砝码进行叠加,每次叠加都与之前所称重量数进行对比,有新的就加入到集合中
for (Integer w : hashSet) {
temp.add(w + weight * j);
}
}
hashSet.addAll(temp);
}
System.out.println(hashSet.size());
}
}
}
查看17道真题和解析
拼多多集团-PDD成长空间 997人发布