-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathsolution031.cpp
More file actions
56 lines (51 loc) · 989 Bytes
/
solution031.cpp
File metadata and controls
56 lines (51 loc) · 989 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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/**
* Next permutation.
* Implements steps:
* Find largest index i where nums[i] < nums[i + 1]
* Find lasgest index j after i where nums[j] > nums[i]
* Swap node nums[i] and nums[j]
* Reverse from index i to the end.
*
* cpselvis([email protected])
* August 31th, 2016
*/
#include<iostream>
#include<vector>
using namespace std;
class Solution {
public:
void nextPermutation(vector<int>& nums) {
int n = nums.size();
int i = n - 1;
int j = n - 1;
while (i > 0)
{
if (nums[i] > nums[i - 1])
{
while (j > i - 1)
{
if (nums[j] > nums[i - 1])
{
swap(nums[i - 1], nums[j]);
reverse(nums.begin() + i, nums.end());
return;
}
j --;
}
}
i --;
}
reverse(nums.begin(), nums.end());
}
};
int main(int argc, char **argv)
{
int arr[3] = {1, 3, 2};
vector<int> vec(arr + 0, arr + 3);
Solution s;
s.nextPermutation(vec);
for (auto i : vec)
{
cout << i << endl;
}
}