[LeetCode] Combinations

77. Combinations

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public:
vector<vector<int>> combine(int n, int k) {
vector<vector<int>> res;
vector<int> tmp;
dfs(res,tmp,k,n,1);
return res;
}

void dfs(vector<vector<int>>& res, vector<int>& tmp, int k, int n, int i) {
if(!k) {
res.push_back(tmp);
return;
}
for(; i <= n - k + 1; i++) {
tmp.push_back(i);
dfs(res, tmp, k - 1, n, i + 1);
tmp.pop_back();
}
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/07/PS/LeetCode/combinations/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.