-
Notifications
You must be signed in to change notification settings - Fork 0
/
next_permutation.cpp
87 lines (78 loc) · 1.92 KB
/
next_permutation.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
// https://oj.leetcode.com/problems/next-permutation/
// Date: Dec 16, 2014
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
void nextPermutation(vector<int> &vec)
{
if (vec.size() <= 1)
{
return;
}
// start iterating backwards
int st_pos = vec.size()-2;
while (st_pos > 0)
{
if (vec[st_pos] < vec[st_pos+1])
{
break;
}
else
{
--st_pos;
}
}
if (vec[st_pos] < vec[st_pos+1])
{
// find the smallest elem in vec[st_pos,...,end] which is > vec[st_pos]
// Then swap these elements
for (int i = vec.size()-1; i != st_pos; --i)
{
if (vec[st_pos] < vec[i])
{
swap(vec[st_pos], vec[i]);
break;
}
}
/*
int swap_pos = vec.size()-1;
for (int i=(vec.size()-1); i >= (st_pos+1); --i)
{
if ((vec[i] > vec[st_pos]) && (vec[i] < vec[swap_pos]))
{
swap_pos = i;
}
}
swap(vec[st_pos], vec[swap_pos]);
*/
++st_pos;
}
// Now reverse the elements
int en_pos = vec.size()-1;
for (int i=0; i <= (en_pos-st_pos)/2; ++i)
{
swap(vec[st_pos+i], vec[en_pos-i]);
}
}
};
int main(int argc, char* argv[])
{
int arr[] = {1,1,5};
vector<int> vec(arr, arr+sizeof(arr)/sizeof(arr[0]));
Solution sln;
sln.nextPermutation(vec);
for (vector<int>::iterator it = vec.begin(); it != vec.end(); ++it)
{
if (it == vec.begin())
{
cout << *it;
}
else
{
cout << "," << *it;
}
}
return 0;
}