题解 | #称砝码#
称砝码
https://www.nowcoder.com/practice/f9a4c19050fc477e9e27eb75f3bfd49c
import java.util.*;
//称砝码 ,这道题采用递归,在当前组砝码搭配前拿到后面组砝码已有所有组合,分别加上自己组的搭配得出结果放进set里去重。注意0称重的利用。
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int [] fama = new int[n];
int [] famaN = new int[n];
for(int i=0;i<n;i++){
fama[i]= in.nextInt();
}
for(int i=0;i<n;i++){
famaN[i]= in.nextInt();
}
HashSet<Integer> result = new HashSet();
result.add(0);
//不放砝码即为0
test(fama,famaN,0,result);
System.out.print(result.size());
}
public static void test ( int [] fama, int [] famaN,int i,HashSet<Integer> resultSet){
if(i+1<fama.length){
test(fama,famaN,i+1,resultSet);
}
HashSet<Integer> resultTempet = new HashSet();
for(int j =0; j<famaN[i];j++){
int result = fama[i]* (j+1);
for(Integer r :resultSet){
resultTempet.add(Integer.valueOf(result+r));
}
}
resultSet.addAll(resultTempet);
}
}
查看9道真题和解析