详情链接:Leetcode 139.组合总和
1.问题思路
组合和排列问题是经典的回溯题,依据递归三部曲
-
确定递归方法参数及返回值。
public void dfs(int[] candidates, int target, int curr, int startIndex)
-
递归终止条件。
当curr > target已经超过了目标值,则不符合条件,需要进行回溯;
当curr = target满足条件,添加至结果集中。
这里注意一点点,数字可以无限制选取,所以每层的一个广度遍历是一致的,不需要过滤使用过的元素。
① 循环的退出条件,累加的数字等于targetNum则追加到结果集,如果大于targetNum则跳出当前层并进行回溯。
② 每层的循环遍历都是从【0, s.length-1】。
2.代码实现
class Solution {
LinkedList<List<Integer>> result = new LinkedList<>();
LinkedList<Integer> path = new LinkedList<>();
public List<List<Integer>> combinationSum(int[] candidates, int target) {
dfs(candidates, target, 0, 0);
return result;
}
public void dfs(int[] candidates, int target, int curr, int startIndex) {
// 终止条件
if(curr > target) {
return;
}
if(curr == target) {
result.add(new ArrayList<>(path));
return;
}
// 水平遍历
for(int i=startIndex; i<candidates.length; i++) {
int item = candidates[i];
curr += item;
path.add(item);
dfs(candidates, target, curr, i);
curr -= item;
path.removeLast();
}
}
}