解题思路
dfs加回溯,思路不好讲出来,可以结合案例看代码
代码
class Solution {
List<List<Integer>> ans;
public List<List<Integer>> combinationSum(int[] candidates, int target) {
ans = new ArrayList<>();
LinkedList<Integer> tem = new LinkedList<>();
backtrack(tem,candidates,target,0,0);
return ans;
}
public void backtrack(LinkedList<Integer> tem,int[] candidates, int target,int cur,int index){
if (cur>target) return;
if (cur==target){
ans.add(new ArrayList<>(tem));
return;
}
for (int i=index;i<candidates.length;i++){
tem.add(candidates[i]);
backtrack(tem, candidates, target, cur+candidates[i],i);
tem.removeLast();//回溯
}
}
}