77 Combinations

1. Question

Given two integersnandk, return all possible combinations ofknumbers out of 1 ...n.
For example, Ifn= 4 and k= 2, a solution is:
1
[
2
[2,4],
3
[3,4],
4
[2,3],
5
[1,2],
6
[1,3],
7
[1,4],
8
]
Copied!

2. Implementation

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

3. Time & Space Complexity

Backtracking: 时间复杂度O(C(n,k)), 空间复杂度O(C(n, k))