List<List<Integer>> res = new ArrayList<>();
int len;
public List<List<Integer>> combinationSum(int[] candidates, int target) {
len = candidates.length;
if(len==0) return res;
//Arrays.sort(candidates);
Deque<Integer> path = new LinkedList<>(); //用双向链表有利于回溯
dfs(candidates, target,0,path);
return res;
}
public void dfs(int[] candidates, int target,int index,Deque<Integer> path){
if(target==0){
res.add(new ArrayList(path));
return;
}
if(target<0) return;
for(int i=index;i<len;i++){
//if(target-candidates[i]<0) break;
path.addLast(candidates[i]);
dfs(candidates,target-candidates[i],i,path);
path.removeLast();
}
}
List<List<Integer>>转换
最新推荐文章于 2024-08-19 20:01:22 发布