39 Combination Sum
39. Combination Sum
1. Question
[
[7],
[2, 2, 3]
]2. Implementation
class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> res = new ArrayList<>();
List<Integer> combinations = new ArrayList<>();
getCombinations(candidates, 0, 0, target, combinations, res);
return res;
}
public void getCombinations(int[] candidates, int index, int sum, int target, List<Integer> combinations, List<List<Integer>> res) {
if (sum > target) {
return;
}
if (sum == target) {
res.add(new ArrayList<>(combinations));
return;
}
for (int i = index; i < candidates.length; i++) {
combinations.add(candidates[i]);
getCombinations(candidates, i, sum + candidates[i], target, combinations, res);
combinations.remove(combinations.size() - 1);
}
}
}3. Time & Space Complexity
Last updated