216 Combination Sum III

1. Question

Find all possible combinations of k numbers that add up to a number n, given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers.
Example 1:
Input: k= 3,n= 7
Output:
1
[[1,2,4]]
Copied!
Example 2:
Input:k= 3,n= 9
Output:
1
[[1,2,6], [1,3,5], [2,3,4]]
Copied!

2. Implementation

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

3. Time & Space Complexity

Backtracking: 时间复杂度O(n^k), 根据组合公式得到,空间复杂度O(n^k)