
解法(回溯方法)
class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target){
// 判断不合法的情况
if(candidates == null || candidates.length == 0){
return null;
}
// 新建List
List<List<Integer>> result = new ArrayList<>();
backtracing(candidates, target, 0, new ArrayDeque<>(), result);
return result;
}
public void backtracing(int[] candidates, int target, int start, Deque<Integer> solution, List<List<Integer>> result){
// 递归结束的条件
if (target < 0){
return;
}
// 回溯满足的条件
if (target == 0){
result.add(new ArrayList<>(solution));
return;
}
// 递归
for(int i = start; i < candidates.length; i++){
solution.push(candidates[i]);
backtracing(candidates, target - candidates[i], i, solution, result);
// 移除已递归元素
solution.pop();
}
}
}
避免重复,所以应该从自己开始,start
本文介绍了一种使用回溯方法解决组合总和问题的算法。通过递归和回溯,该算法能够找到所有可能的数列组合,使得数列中数字的总和等于给定的目标值。代码示例详细展示了如何实现这一过程。
654

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



