代码(未剪枝)
class Solution {
List<List<Integer>> res = new ArrayList<>();
List<Integer> path = new ArrayList<>();
public List<List<Integer>> combinationSum(int[] candidates, int target) {
Arrays.sort(candidates);
backtracking(candidates, target, 0, 0);
return res;
}
public void backtracking(int[] candidates, int target, int sum, int startIndex) {
if (sum > target) return;
if (sum == target) res.add(new ArrayList<>(path));
for (int i = startIndex; i <= candidates.length - 1; i ++) {
sum += candidates[i];
path.add(candidates[i]);
backtracking(candidates, target, sum, i);
path.remove(path.size() - 1);
sum -= candidates[i];
}
}
}