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);
}
}
}
精髓
其實(shí)是DFS蛮原,所謂的回溯法枫笛,為一個(gè)滿N叉樹(shù)通今,但是要按數(shù)組的形式實(shí)現(xiàn),這里剪枝其實(shí)就是target<0