AC代码
import java.util.*;
class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> ans = new ArrayList<>();
if(candidates == null || candidates.length == 0) {
return ans;
}
ArrayList<Integer> tmp = new ArrayList<>();
backTrack(candidates, target, 0, tmp, ans);
return ans;
}
private void backTrack(int[] candidates, int target, int nowStart, ArrayList<Integer> tmp,
List<List<Integer>> ans) {
if(target < 0) {
return;
}
if(target == 0) {
ans.add(new ArrayList<>(tmp));
return;
}
for(int start = nowStart; start < candidates.length; start++) {
tmp.add(candidates[start]);
backTrack(candidates, target - candidates[start], start, tmp, ans);
tmp.remove(tmp.size() - 1);
}
}
}
精髓
其实是DFS,所谓的回溯法,为一个满N叉树,但是要按数组的形式实现,这里剪枝其实就是target<0