称砝码, 华为

在原有重量基础上增加一种重量的砝码,依次使用0,..., m【i】个,得到新的重量,将这些重量添加到集合中,继续重复。

import java.util.*;
public class Main {
    static int solution(int n, int[] m, int[] x){
        Set<Integer> set = new HashSet<>();
        set.add(0);
        for(int i=0; i < n; i++){
            List<Integer> list = new ArrayList<>();
            for(int j=0; j <= x[i]; j++) {
                int weight = j * m[i];
                for(int w : set) {
                    list.add(w + weight);
                }
            }
            for(int k=0; k < list.size(); k++)
                set.add(list.get(k));
        }
        return set.size();
    }
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while(sc.hasNext()){
            int n = sc.nextInt();
            int[] m = new int[n];
            int[] x = new int[n];
            for(int i=0; i < n; i++) 
                m[i] = sc.nextInt();
            for(int i=0; i < n; i++)
                x[i] = sc.nextInt();
            int res = solution(n, m, x);
            System.out.println(res);
        }
    }
}
原文地址:https://www.cnblogs.com/lixyuan/p/13275302.html