39. 组合总和
使用dfs算法,遍历出结果,然后再剪枝
代码
class Solution {
private List<List<Integer>> res = new ArrayList<>();
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<Integer> list = new ArrayList<>();
dfs(candidates, list, 0, target,0);
return res;
}
public void dfs(int[] candidates, List<Integer> list, int num, int target,int startIndex) {
int n = candidates.length;
// dfs出口
if (num == target) {
List<Integer> ans = new ArrayList<>(list);
res.add(ans);
return;
}
if (num > target) {
return;
}
// 遍历每个数字
for (int i = startIndex; i < n; i++) {
list.add(candidates[i]);
dfs(candidates, list, num + candidates[i], target,i);
list.remove(list.size() - 1);
}
}
}