kniost

谁怕,一蓑烟雨任平生

0%

LeetCode 77. Combinations

77. Combinations

Difficulty: Medium

Given two integers n and k, return all possible combinations of k numbers out of 1 … n.

Example:

1
2
3
4
5
6
7
8
9
10
Input: n = 4, k = 2
Output:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]

Solution

Language: Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public List<List<Integer>> combine(int n, int k) {
List<List<Integer>> result = new ArrayList<>();
if (n <= 0 || k <= 0) {
return result;
}

helper(1, n, k, result, new ArrayList<>(k));
return result;
}

private void helper(int cur, int n, int k, List<List<Integer>> result, List<Integer> one) {
if (k == 0) {
result.add(new ArrayList<>(one));
return;
}
for (int i = cur; i <= n; i++) {
one.add(i);
helper(i + 1, n, k - 1, result, one);
one.remove(one.size() - 1);
}
}
}
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<>();
if (n <= 0 || k <= 0) {
return result;
}

helper(1, n, k, result, new int[k], 0);
return result;
}

private void helper(int cur, int n, int k, List<List<Integer>> result, int[] one, int index) {
if (k == 0) {
List<Integer> tmp = new ArrayList<>(k);
for (int a : one) {
tmp.add(a);
}
result.add(tmp);
return;
}
for (int i = cur; i <= n; i++) {
one[index++] = i;
helper(i + 1, n, k - 1, result, one, index);
index--;
}
}
}