
1.简单DFS+回溯

class Solution {
LinkedList<Integer> path = new LinkedList<>();
List<List<Integer>> res = new ArrayList<>();
public List<List<Integer>> combinationSum(int[] candidates, int target) {
dfs(candidates, 0, 0, target);
return res;
}
public void dfs(int[] candidates, int start, int curSum, int target) {
if (curSum > target) {
return;
}
if (curSum == target) {
res.add(new ArrayList<>(path));
return;
}
for (int i = start; i < candidates.length; i++) {
path.add(candidates[i]);
dfs(candidates, i, curSum + candidates[i], target);
path.removeLast();
}
}
}
2.剪枝后

class Solution {
LinkedList<Integer> path = new LinkedList<>();
List<List<Integer>> res = new ArrayList<>();
public List<List<Integer>> combinationSum(int[] candidates, int target) {
dfs(candidates, 0, 0, target);
return res;
}
public void dfs(int[] candidates, int start, int curSum, int target) {
if (curSum > target) {
return;
}
if (curSum == target) {
res.add(new ArrayList<>(path));
return;
}
for (int i = start; i < candidates.length; i++) {
if (curSum + candidates[i] > target) {
continue;
}
path.add(candidates[i]);
dfs(candidates, i, curSum + candidates[i], target);
path.removeLast();
}
}
}