🔗:参考的题解:LeetCode39- 组合总和
class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<Integer> path=new ArrayList<>();
List<List<Integer>> paths=new ArrayList<>();
Arrays.sort(candidates);
dfs(candidates,0,paths,path,target);
List<List<Integer>> res = new ArrayList(paths);
return res;
}
public void dfs(int[] candidates , int begin, List<List<Integer>> paths ,List<Integer> path ,int num){
if(num==0&&!path.isEmpty()){
paths.add(new ArrayList<>(path));
return;
}
for( int i = begin ; i<candidates.length;++i){
int next_num = num-candidates[i];
if(next_num<0){
break;
}
path.add(candidates[i]);
dfs(candidates,i,paths,path, next_num);
if (!path.isEmpty()) {
path.remove(path.size()-1);
}
}
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33