题解 | #称砝码#

称砝码

https://www.nowcoder.com/practice/f9a4c19050fc477e9e27eb75f3bfd49c

import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int[] weights = new int[n];
        int[] amount = new int[n];
        for (int i = 0; i < n; i++) {
            weights[i] = sc.nextInt();
        }
        for (int i = 0; i < n; i++) {
            amount[i] = sc.nextInt();
        }
        Set<Integer> set = new HashSet<Integer>() {{
            add(0);
        }};
        for (int i = 0; i < n; i++) {
            // 获取当前结果集
            List<Integer> list = new ArrayList<>(set);
            for (int j = 1; j <= amount[i]; j++) {
                for (Integer weight : list) {
                    set.add(weight + weights[i] * j);
                }
            }
        }
        System.out.println(set.size());
    }
}

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务