在给定的数中,找到所以加起来的和恰好等于指定的数的数集。
import java.util.ArrayList;
import java.util.List;
public class a {
public static void main(String[] args) {
int[] nums = {2, 4, 5,6, 3, 7}; // 给定的一堆数
int targetSum = 9; // 指定的和
List<List<Integer>> result = new ArrayList<>(); // 用于存储结果的列表
backtrack(nums, targetSum, 0, new ArrayList<>(), result); // 调用回溯方法查找满足条件的组合
// 输出结果
for (List<Integer> combination : result) {
System.out.println(combination);
}
}
private static void backtrack(int[] nums, int target, int start, List<Integer> path, List<List<Integer>> result) {
// 如果目标和为0,表示找到了满足条件的组合,将其添加到结果列表中
if (target == 0) {
result.add(new ArrayList<>(path));
return;
}
// 从起始位置开始遍历数组
for (int i = start; i < nums.length; i++) {
// 如果当前数字小于等于目标和,则选择当前数字进行组合
if (nums[i] <= target) {
// 选择当前数字
path.add(nums[i]);
// 继续向下搜索,但是起始位置从i+1开始,避免重复使用同一个数字
backtrack(nums, target - nums[i], i + 1, path, result);
// 回溯,撤销选择,继续尝试其他可能的组合
path.remove(path.size() - 1);
for (int num : path) {
System.out.println(num);
}
}
}
}
}