-
Notifications
You must be signed in to change notification settings - Fork 0
/
permutations.cc
45 lines (41 loc) · 1.43 KB
/
permutations.cc
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
#include "leetcode.h"
using namespace std;
class Solution {
public:
vector<vector<int>> permute(vector<int> &numbers) const {
switch (numbers.size()) {
case 0: return {};
case 1: return {numbers};
case 2: return {numbers, {numbers[1], numbers[0]}};
default: {
vector<vector<int>> res;
uint64_t count = 1;
for (size_t i = 2; i <= numbers.size(); ++i) { count *= i; }
res.reserve(count);
permute_recursion(numbers, 0, res);
return res;
}
}
}
void permute_recursion(vector<int> &numbers, const size_t hierarchy, vector<vector<int>> &out) const {
if (hierarchy + 1 == numbers.size()) {
out.emplace_back(numbers);
} else {
permute_recursion(numbers, hierarchy + 1, out);
for (auto x = hierarchy + 1; x < numbers.size(); ++x) {
std::swap(numbers[x], numbers[hierarchy]);
permute_recursion(numbers, hierarchy + 1, out);
std::swap(numbers[x], numbers[hierarchy]);
}
}
}
};
int main(int argc, char const *argv[]) {
Solution solution;
vector<int> numbers{1, 2, 3};
auto res = solution.permute(numbers);
for (auto &&vector : res) {
for (auto &&value : vector) { cout << value << " "; }
cout << endl;
}
}