-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNextPermutation.cc
76 lines (57 loc) · 1.26 KB
/
NextPermutation.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#include <vector>
#include <string>
#include <iostream>
using std::vector;
using std::string;
using std::cout;
using std::endl;
#include <cstdlib>
using std::atoi;
struct ListNode{
int val;
ListNode *next;
ListNode(int x):val(x), next(NULL){}
};
#include <algorithm>
#include <cstring>
template<typename RAIter, typename Comp = std::less<typename std::iterator_traits<RAIter>::value_type> >
void next_permutaion(RAIter first, RAIter end, Comp cmp = Comp()){
auto p = end - 1;
if(first == end || first == p){
return;
}
for(; p > first; --p){
if(cmp(*(p - 1), *p))break;
}
if(p > first){
auto q = p - 1;
auto e = end - 1;
for(; e > q; --e){
if(cmp(*q, *e))break;
}
std::swap(*q, *e);
}
for(auto q = end - 1; p < q; ++p, --q){
std::swap(*p, *q);
}
//reverse:
}
class Solution{
public:
void nextPermutation(vector<int> &num){
next_permutaion(num.begin(), num.end());
}
};
int main(){
Solution slu;
using std::cin;
vector<int> num = {1,2,3};
for(int i = 0; i < 18; ++i){
slu.nextPermutation(num);
for(auto &n: num){
cout << n << " ";
}
cout << endl;
}
return 0;
}