![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/457888ec6c6125e79795b19c40ad8e0e.png)
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/11e10d98dcde69360388a432f9bc1039.png)
List<Value> result;
void backtrack(路径, 选择列表){
if(满足条件){
result.add(路径);
return;
}
for (选择:选择列表){
做选择;
backtrack(路径,选择列表);
撤销选择;
}
}
void traverse(TreeNode root){
if (root == null){
return;
}
for (TreeNode child:root.children()){
traverse(child);
}
}
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;
public class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
int len = candidates.length;
List<List<Integer>> res = new ArrayList<>();
if (len == 0) {
return res;
}
Deque<Integer> path = new ArrayDeque<>();
dfs(candidates, 0, len, target, path, res);
return res;
}
private void dfs(int[] candidates, int begin, int len, int target, Deque<Integer> path, List<List<Integer>> res) {
if (target < 0) {
return;
}
if (target == 0) {
res.add(new ArrayList<>(path));
return;
}
for (int i = begin; i < len; i++) {
path.addLast(candidates[i]);
dfs(candidates, i, len, target - candidates[i], path, res);
path.removeLast();
}
}
}
作者:liweiwei1419
链接:https://leetcode-cn.com/problems/combination-sum/solution/hui-su-suan-fa-jian-zhi-python-dai-ma-java-dai-m-2/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。