题解 | #HJ041 称砝码#

称砝码

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

import java.util.*;

/**
 * HJ41 称砝码
 */
public class HJ041 {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNextInt()) { // 注意 while 处理多个 case
            HashSet<Integer> set = new HashSet<>();//存放所有可能的结果,不用担心重复问题
            set.add(0);//初始化为0
            int n = sc.nextInt();//个数
            int[] w = new int[n];
            int[] nums = new int[n];
            for (int i = 0; i < n; i++) {
                w[i] = sc.nextInt();//砝码的重量
            }
            for (int i = 0; i < n; i++) {
                nums[i] = sc.nextInt();//砝码个数
            }
            for (int i = 0; i < n; i++) {//遍历砝码
                ArrayList<Integer> list = new ArrayList<>(set);//取当前所有的结果
                for (int j = 1; j <= nums[i]; j++) {//遍历个数
                    for (Integer integer : list) {
                        set.add(integer + w[i] * j);
                    }
                }
            }
            System.out.println(set.size());
        }
        sc.close();
    }
}
全部评论

相关推荐

少年郎as:这不把公司名贴出来那我可要喷你了哦
点赞 评论 收藏
分享
评论
1
1
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务