-
Notifications
You must be signed in to change notification settings - Fork 0
/
31. Next Permutation
81 lines (62 loc) · 1.44 KB
/
31. Next Permutation
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
const int ZERO = [](){
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
return 0;
}();
class Solution {
public:
void nextPermutation1(vector<int>& nums)
{
int n = (int)nums.size();
if(n < 2)
{
return;
}
int i = n - 2;
while(i >= 0 && nums[i] >= nums[i + 1])
{
--i;
}
if(i < 0)
{
reverse(nums.begin(), nums.end());
return;
}
int j = n - 1;
while(j > i && nums[j] <= nums[i])
{
j--;
}
std::swap(nums[i], nums[j]);
reverse(nums.begin() + i + 1, nums.end());
}
void nextPermutation(vector<int>& nums)
{
auto first = nums.begin(), after = nums.end(), cur = after;
while(true)
{
--cur;
if(cur == first)
{
reverse(first, after);
return;
}
auto prev = cur;
--prev;
if(*prev < *cur)
{
auto i = after;
while(true)
{
--i;
if(*i > *prev)
{
swap(*i, *prev);
reverse(cur, after);
return;
}
}
}
}
}
};