-
Notifications
You must be signed in to change notification settings - Fork 28
/
Combinations.cpp
49 lines (45 loc) · 1.46 KB
/
Combinations.cpp
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
class Solution {
public:
void combineUtils(int idx, int n, int k, vector<int> &solution, vector<vector<int> > &result) {
if(solution.size() == k) {
result.push_back(solution);
return;
}
for(int i = idx; i <= n; ++i) {
solution.push_back(i);
combineUtils(i + 1, n, k, solution, result);
solution.pop_back();
}
}
vector<vector<int> > combine(int n, int k) {
vector<vector<int> > result;
vector<int> solution;
if(k == 0 or n == 0) return result;
combineUtils(1, n, k, solution, result);
return result;
}
};
// Alternatives
class Solution {
public:
void combineUtils(int idx, int n, int k, vector<int> &solution, vector<vector<int> > &result) {
if(idx > n or solution.size() == k) {
if(solution.size() == k)
result.push_back(solution);
return;
}
if(solution.size() < k) {
solution.push_back(idx);
combineUtils(idx + 1, n, k, solution, result);
solution.pop_back();
}
combineUtils(idx + 1, n, k, solution, result);
}
vector<vector<int> > combine(int n, int k) {
vector<vector<int> > result;
vector<int> solution;
if(k == 0 or n == 0) return result;
combineUtils(1, n, k, solution, result);
return result;
}
};