-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCombinations.java
More file actions
39 lines (34 loc) · 818 Bytes
/
Combinations.java
File metadata and controls
39 lines (34 loc) · 818 Bytes
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
/*
Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.
Example:
Input: n = 4, k = 2
Output:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]
time = O(n^2)
space = O(n)
*/
class Solution {
public List<List<Integer>> combine(int n, int k) {
List<List<Integer>> result = new ArrayList<>();
dfs(result, new ArrayList<>(), 1, n, k);
return result;
}
private void dfs(List<List<Integer>> result, List<Integer> list, int start, int n, int k) {
if (list.size() == k) {
result.add(new ArrayList<>(list));
return;
}
for (int i = start; i <= n; i++) {
list.add(i);
dfs(result, list, i + 1, n, k);
list.remove(list.size() - 1);
}
}
}