MrainW's Home

All things come to those who wait!

0%

LeetCode 77. Combinations

Question

Given two integers n and k, return all possible combinations of k numbers out of the range [1, n].

You may return the answer in any order.

https://leetcode.com/problems/combinations

  • Solution1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public List<List<Integer>> combine(int n, int k) {
List<List<Integer>> res = new ArrayList<>();
dfs(res, new ArrayList<>(), n, k, 1);
return res;
}
private void dfs(List<List<Integer>> res, List<Integer> level, int n, int k, int index){
if (level.size() == k) res.add(new ArrayList<>(level));
else{
for (int i = index; i <= n; i++){
level.add(i);
dfs(res, level, n, k, i + 1);
level.remove(level.size() - 1);
}
}
}
}

Complexity:

Time complexity: O(C(n, k))

Space complexity: O(k)

Welcome to my other publishing channels