forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
combinations.cpp
66 lines (62 loc) · 1.92 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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
// Time: O(k * C(n, k))
// Space: O(k)
class Solution {
public:
vector<vector<int>> combine(int n, int k) {
static const auto& add_result =
[](const auto& nums, const auto& idxs, auto *result) {
result->emplace_back();
transform(cbegin(idxs), cend(idxs), back_inserter(result->back()),
[&nums](const auto& i) {
return nums[i];
});
};
static const auto& next_pos =
[](const auto& n, const auto& k, const auto& idxs) {
int i = k - 1;
for (; i >= 0; --i) {
if (idxs[i] != i + n - k) {
break;
}
}
return i;
};
if (k > n) {
return {};
}
vector<int> nums(n), idxs(k);
iota(begin(nums), end(nums), 1), iota(begin(idxs), end(idxs), 0);
vector<vector<int>> result;
add_result(nums, idxs, &result);
for (int i; (i = next_pos(n, k, idxs)) >= 0;) {
++idxs[i];
for (int j = i + 1; j < k; ++j) {
idxs[j] = idxs[j - 1] + 1;
}
add_result(nums, idxs, &result);
}
return result;
}
};
// Time: O(n!)
// Space: O(n)
class Solution2 {
public:
void dfs(int n, int k, int start, vector<int> &path, vector<vector<int> > &ans) {
if(k == 0) {
ans.push_back(path);
return;
}
for(int i = start; i <= n; ++i) {
path.push_back(i);
dfs(n, k - 1, i + 1, path, ans);
path.pop_back();
}
}
vector<vector<int> > combine(int n, int k) {
vector<vector<int> > ans;
vector<int> path;
dfs(n, k, 1, path, ans);
return ans;
}
};