暴力递归:利用set去重,递归加上砝码重量即可。
public class Main {
static Set<Integer> set = new HashSet<>();
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNextInt()) { // 注意 while 处理多个 case
int n = in.nextInt();
int m[] =new int[n];
int x[] = new int[n];
for(int i =0;i<n;++i){
m[i] = in.nextInt();
}
for(int i =0;i<n;++i){
x[i] = in.nextInt();
}
func(m,x,0,0);
System.out.println(set.size());
}
}
public static void func(int[] m ,int[]x,int index,int weight){
if(index==x.length){
return ;
}
if(!set.contains(weight))set.add(weight);
if(x[index]>0){
x[index]--;
func(m,x,index,weight+m[index]);
x[index]++;
}
func(m,x,index+1,weight);
}
}