Combination Sum
Example
Input:
candidates = [2,3,6,7], target = 7
A solution set is:
[
[7],
[2,2,3]
]Input: candidates = [2,3,5], target = 8
A solution set is:
[
[2,2,2,2],
[2,3,3],
[3,5]
]Note
Code
Last updated
Input:
candidates = [2,3,6,7], target = 7
A solution set is:
[
[7],
[2,2,3]
]Input: candidates = [2,3,5], target = 8
A solution set is:
[
[2,2,2,2],
[2,3,3],
[3,5]
]Last updated
i != 0 && candidates[i] == candidates[i - 1]candidates[i] > target 或 target < 0 (作为递归出口)public class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> result = new ArrayList<>();
if (candidates == null) {
return result;
}
List<Integer> combination = new ArrayList<>();
Arrays.sort(candidates);
helper(candidates, 0, target, combination, result);
return result;
}
private void helper(int[] candidates, int index, int target,
List<Integer> combination, List<List<Integer>> result) {
if (target == 0) {
result.add(new ArrayList<Integer>(combination));
return;
}
for (int i = index; i < candidates.length; i++) {
if (candidates[i] > target) {
break;
}
if (i != 0 && candidates[i] == candidates[i - 1]) {
continue;
}
combination.add(candidates[i]);
helper(candidates, i, target - candidates[i], combination, result);
combination.remove(combination.size() - 1);
}
}
}