题解 | #称砝码#
称砝码
https://www.nowcoder.com/practice/f9a4c19050fc477e9e27eb75f3bfd49c
思路:依次遍历砝码,将砝码重量的组合存入到set中,对每一个砝码,都可以与之前已经存入set的重量组合再次进行组合,所以对于第i个砝码,需要先将前面i-1个砝码的重量组合先存入到临时tempSet中,再将其与第i个砝码进行组合的值放入set中
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNextLine()) {
//依次读取砝码种数、重量、数量
int n = Integer.parseInt(sc.nextLine().trim());
String[] m = sc.nextLine().split("\\s+");
String[] x = sc.nextLine().split("\\s+");
//将砝码的重量按其个数存入list中
ArrayList<Integer> list = new ArrayList<>();
for (int i = 0; i < n; i++) {
int weight = Integer.parseInt(m[i]);
int num = Integer.parseInt(x[i]);
for (int j = 0; j < num; j++) {
list.add(weight);
}
}
//用能自动去重的set来存放砝码的重量组合,先放入0到set中
Set<Integer> set = new HashSet<>();
set.add(0);
//对存放砝码重量的list进行遍历
for (int i = 0; i < list.size(); i++) {
//对每一个砝码,都可以与已存入set的重量值进行组合(即将重量相加)
//故先将原set的重量值复制到临时tempSet中,对其进行遍历
Set<Integer> tempSet = new HashSet<>(set);
for (int v : tempSet) {
set.add(v + list.get(i));
}
}
//最终得到的set的大小即为重量组合的个数
System.out.println(set.size());
}
}
}
查看15道真题和解析