077.Combinations

Solution 1: accepted 28ms

DFS.

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
class Solution {
public List<List<Integer>> combine(int n, int k) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
List<Integer> list = new ArrayList<>();
if (n == 0) {
return result;
}
comboHelper(result, list, n, k);
return result;
}
private void comboHelper(List<List<Integer>> result,
List<Integer> list,
int n,
int k) {
if (k == 0) {
result.add(new ArrayList<>(list));
} else {
for (int i = n; i > 0; i--) {
list.add(i);
comboHelper(result, list, i - 1, k - 1);
list.remove(list.size() - 1);
}
}
}
}