1. 题目
读题
考查点
2. 解法
思路
- 1. 暴力破解,3重循环
- 2. 利用set 去重
可参照
【Java 数据结构及算法实战】系列 045:HJ41 称砝码-华为开发者论坛 | 华为开发者联盟 (huawei.com)
代码逻辑
具体实现
public class HJ041 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] w = new int[n];
for (int i = 0; i < n; i++) {
w[i] = sc.nextInt();
}
int[] nums = new int[n];
for (int i = 0; i < n; i++) {
nums[i] = sc.nextInt();
}
System.out.println(getWays(w, nums, n));
}
public static int getWays(int[] w, int[] nums, int n) {
Set<Integer> set = new HashSet<>();
set.add(0);
for (int i = 0; i < n; i++) {
List<Integer> list = new ArrayList<>(set);
for (int j = 0; j <= nums[i]; j++) {
for (int k = 0; k < list.size(); k++) {
set.add(list.get(k) + j * w[i]);
}
}
}
return set.size();
}
}