39 Combination Sum

1. Question

Given a set of candidate numbers (C)(without duplicates)and a target number (T), find all unique combinations inCwhere the candidate numbers sums toT.
Thesamerepeated number may be chosen fromCunlimited number of times.
Note:
  • All numbers (including target) will be positive integers.
  • The solution set must not contain duplicate combinations.
For example, given candidate set[2, 3, 6, 7]and target7, A solution set is:
1
[
2
[7],
3
[2, 2, 3]
4
]
Copied!

2. Implementation

(1) Backtracking
1
class Solution {
2
public List<List<Integer>> combinationSum(int[] candidates, int target) {
3
List<List<Integer>> res = new ArrayList<>();
4
List<Integer> combinations = new ArrayList<>();
5
getCombinations(candidates, 0, 0, target, combinations, res);
6
return res;
7
}
8
9
public void getCombinations(int[] candidates, int index, int sum, int target, List<Integer> combinations, List<List<Integer>> res) {
10
if (sum > target) {
11
return;
12
}
13
14
if (sum == target) {
15
res.add(new ArrayList<>(combinations));
16
return;
17
}
18
19
for (int i = index; i < candidates.length; i++) {
20
combinations.add(candidates[i]);
21
getCombinations(candidates, i, sum + candidates[i], target, combinations, res);
22
combinations.remove(combinations.size() - 1);
23
}
24
}
25
}
Copied!

3. Time & Space Complexity

Backtracking: 时间复杂度O(2^n), 空间复杂度O(2^n)