[LeetCode] Problem 77 - Combinations

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

Example

Input: n = 4, k = 2

Output:

1
2
3
4
5
6
7
8
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public List<List<Integer>> combine(int n, int k) {
List<List<Integer>> result = new ArrayList<>();

combineHelper(result, new ArrayList<>(), n, k, 1);

return result;
}

private void combineHelper(List<List<Integer>> result, List<Integer> combination, int n, int k, int idx) {
if (combination.size() == k) {
result.add(new ArrayList<>(combination));
return;
}

for (int i = idx; i <= n; i++) {
combination.add(i);
combineHelper(result, combination, n, k, i + 1);
combination.remove(combination.size() - 1);
}
}