[LeetCode][216. Combination Sum III] 2 Approaches: Backtracking and Bit Mask
By Long Luo
This article is the solution 2 Approaches: Backtracking and Bit Mask of Problem 216. Combination Sum III .
Here shows 2 Approaches to slove this problem: Backtracking and Bit Mask.
Backtracking
A very easy backtracking solution. Just refer to 17. Letter Combinations of a Phone Number.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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43public List<List<Integer>> combinationSum3(int k, int n) {
List<List<Integer>> ans = new ArrayList<>();
// corner cases
if (k <= 0 || n <= 0 || k > n) {
return ans;
}
// The upper bound of n: [9, 8, ... , (9 - k + 1)], sum is (19 - k) * k / 2
if (n > (19 - k) * k / 2) {
return ans;
}
backtrack(ans, new ArrayList<>(), 1, k, n);
return ans;
}
public void backtrack(List<List<Integer>> res, List<Integer> path, int start, int k, int target) {
if (k < 0 || target < 0) {
return;
}
if (k == 0 && target == 0) {
res.add(new ArrayList<>(path));
return;
}
for (int i = start; i <= 9; i++) {
// trim
if (i > target) {
break;
}
// trim
if (target - i == 0 && k > 1) {
break;
}
path.add(i);
backtrack(res, path, i + 1, k - 1, target - i);
path.remove(path.size() - 1);
}
}
Analysis
- Time Complexity: \(O({M \choose k} \times k)\) , \(M\) is the size of combinations, \(M = 9\), the total combinations is \(M \choose k\).
- Space Complexity: \(O(M + k)\) , size of \(path\) is \(k\) , the recursion stack is \(O(M)\) .