leetcode题目链接
1. 题目考点
- dfs + 剪枝
- 回溯
1. 考点解析
- 回溯 + 剪枝
class Solution {
List<List<Integer>> res = new ArrayList<>();
public List<List<Integer>> combinationSum(int[] candidates, int target) {
Arrays.sort(candidates);
Stack<Integer> path = new Stack<>();
dfs(candidates, 0, target, path, 0);
return res;
}
public void dfs(int[] candidates, int start, int target, Stack<Integer> path, int sum) {
if (sum == target) {
res.add(new ArrayList(path));
return ;
}
if (sum > target) return ;
for (int i = start; i < candidates.length; i++) {
sum += candidates[i];
path.push(candidates[i]);
dfs(candidates, i, target, path, sum);
sum -= candidates[i];
path.pop();
}
}
}