华为OD机试 2025A卷题库疯狂收录中,刷题点这里
本专栏收录于《华为OD机试(JAVA)真题(A卷+E卷+B卷+C卷+D卷)》。
刷的越多,抽中的概率越大,私信哪吒,备注华为OD,加入华为OD刷题交流群,每一题都有详细的答题思路、详细的代码注释、3个测试用例、为什么这道题采用XX算法、XX算法的适用场景,发现新题目,随时更新,全天CSDN在线答疑。
给定一个整数数组nums、一个数字k,一个整数目标值target,请问nums中是否存在k个元素,使其相加结果为target,请输出所有符合条件且不重复的k元组的个数。
取值范围:
2 <= nums.length <= 200
-109 < numslil < 109
-109 < target< 109
2 <= k <= 100
第一行输入整数数组nums;
第二行输入数字k;
第三行输入整数目标值target;
输出第一行是符合要求的元组个数。
-1 -2 -3 4 5
2
2
2
符合条件的2元组为:( -1, 3) 和 (-2, 4)。注意数组中没有3,因此只有一种有效的组合,可能需要修正代码。
0 0 0 0
2
0
1
符合条件的2元组为:(0,0)。尽管有多个0,去重后只有一个唯一的元组。
// 符合条件的数量
public static int okSum = 0;
public static int target;
public static List<List<Integer>> numsList = new ArrayList<>();
/**
* 从nums数组中取k个数,使其和等于target
*/
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// 整数数组nums
int[] nums = Arrays.stream(sc.nextLine().split(" ")).mapToInt(Integer::parseInt).toArray();
// 输入数字k
int k = sc.nextInt();
// 输入整数目标值target
target = sc.nextInt();
calculate(nums, k, new ArrayList<>(), 0);
System.out.println(okSum);
}
/**
* @param nums 数组
* @param n n个数
* @param list 选取的数字
* @param index 数组的索引
*/
public static void calculate(int[] nums, int n, List<Integer> list, int index) {
if (n == 0) {
int count = 0;
// 集合内数字之和
for (Integer i : list) {
count += i;
}
// 符合条件且不重复
if (count == target && !isContains(list)) {
numsList.add(new ArrayList<>(list));
okSum++;
}
} else {
for (int i = index; i < nums.length; i++) {
list.add(nums[i]);
calculate(nums, n - 1, list, i + 1);
list.remove(list.size() - 1);
}
}
}
/**
* 集合是否重复
*/
public static boolean isContains(List<Integer> list) {
Collections.sort(list);
for (List<Integer> temp : numsList) {
Collections.sort(temp);
if (list.size() == temp.size()) {
if (list.containsAll(temp)) {
return true;
}
}
}
return false;
}
1 2 5 8 4
2
9
2
[1,8],[5,4]满足条件。
下一篇:华为OD机试 - 简易内存池 - 逻辑分析(Java 2025 A卷 200分)
本文收录于,华为OD机试(JAVA)真题(A卷+E卷+B卷+C卷+D卷)
刷的越多,抽中的概率越大,私信哪吒,备注华为OD,加入华为OD刷题交流群,每一题都有详细的答题思路、详细的代码注释、3个测试用例、为什么这道题采用XX算法、XX算法的适用场景,发现新题目,随时更新,全天CSDN在线答疑。