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();
}
}
2021-06-05
最新推荐文章于 2021-11-09 20:10:55 发布
这篇博客探讨了一种使用深度优先搜索(DFS)解决组合总和问题的方法。给定一个由正整数组成的候选人数组和一个目标整数,目标是找出所有可能的组合,使得候选数组中的整数之和等于目标值。代码中首先对数组进行排序,然后通过递归的DFS遍历所有可能的路径,并利用剪枝技巧优化搜索过程。博客内容详细解释了算法的实现和工作原理。
摘要由CSDN通过智能技术生成