给你一个 无重复元素 的整数数组 candidates 和一个目标整数 target ,找出 candidates 中可以使数字和为目标数 target 的 所有 不同组合 ,并以列表形式返回。你可以按 任意顺序 返回这些组合。
candidates 中的 同一个 数字可以 无限制重复被选取 。如果至少一个数字的被选数量不同,则两种组合是不同的。
对于给定的输入,保证和为 target 的不同组合数少于 150 个。
示例 1:
输入:candidates = [2,3,6,7], target = 7
输出:[[2,2,3],[7]]
解释:
2 和 3 可以形成一组候选,2 + 2 + 3 = 7 。注意 2 可以使用多次。
7 也是一个候选, 7 = 7 。
仅有这两种组合。
示例 2:
输入: candidates = [2,3,5], target = 8
输出: [[2,2,2,2],[2,3,3],[3,5]]
示例 3:
输入: candidates = [2], target = 1
输出: []
使用回溯大法:
class Solution {
static Stack<Integer> stack = new Stack<>();
public List<List<Integer>> combinationSum(int[] candidates, int target) {
stack = new Stack();
List<List<Integer>> list = new ArrayList<>();
dfs(candidates, target, 0, 0, list);
return list;
}
public void dfs(int[] candidates, int target, int sum, int start, List<List<Integer>> list) {
if (target == sum) {
List<Integer> l = new ArrayList<>();
for (Integer i : stack) {
l.add(i);
}
list.add(l);
return;
}
if (target < sum) {
return;
}
for (int i = start; i < candidates.length; i++) {
sum = sum + candidates[i];
//加入栈
stack.push(candidates[i]);
dfs(candidates, target, sum, i, list);
//回溯
sum = sum - candidates[i];
stack.pop();
}
}
}
本文介绍了一种解决组合求和问题的算法实现,通过回溯法寻找所有可能的数字组合,使得这些数字之和等于目标值。文章提供了具体的Java代码示例,并通过几个实例展示了如何运用该算法。
2416

被折叠的 条评论
为什么被折叠?



