39. 组合总和
回溯
class Solution {
List<List<Integer>> res = new ArrayList<>();
List<Integer> path = new ArrayList<>();
public List<List<Integer>> combinationSum(int[] candidates, int target) {
backtrack(candidates, target, 0);
return res;
}
void backtrack(int[] candidates, int target, int ind){
if(target < 0) return;
if(target == 0){
res.add(new ArrayList<>(path));
return;
}
for(int i = ind; i < candidates.length; i++){
path.add(candidates[i]);
target -= candidates[i];
backtrack(candidates, target, i);
target += candidates[i];
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