-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathpermutations_iterative.cpp
More file actions
41 lines (36 loc) · 938 Bytes
/
permutations_iterative.cpp
File metadata and controls
41 lines (36 loc) · 938 Bytes
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
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
template <typename T>
vector<vector<T>> generatePermutations(vector<T> arr) {
vector<vector<T>> permutations;
sort(arr.begin(), arr.end());
permutations.push_back(arr);
while (true) {
int i = arr.size()-2;
while (i >= 0 && arr[i] >= arr[i + 1]) {
i--;
}
if (i < 0) break;
int j = arr.size()-1;
while (arr[j] <= arr[i]) {
j--;
}
swap(arr[i], arr[j]);
reverse(arr.begin() + i + 1, arr.end());
permutations.push_back(arr);
}
return permutations;
}
int main() {
vector<int> arr = {1, 3, 2};
vector<vector<int>> permutations = generatePermutations(arr);
for (const auto& perm : permutations) {
for (const auto& elem : perm) {
cout << elem << " ";
}
cout << endl;
}
return 0;
}