-
Notifications
You must be signed in to change notification settings - Fork 0
/
next_pre_permutation.cpp
48 lines (39 loc) · 1.18 KB
/
next_pre_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
[i]<s[i+1]。如果不存在,
则表明该permutation已经最大,next permutation为当前序列的逆序。
2. 在s[i+1:n-1]中找一个j,使s[j]>s[i]>=s[j+1],swap(s[i], s[j])
3. 将s[i+1:n-1]排序,从低位到高位单调递减。
class Solution {
public:
void nextPermutation(vector<int> &num) {
if(num.size()<2) return;
int n = num.size(), j = n-2;
while(j>=0 && num[j]>=num[j+1]) j--;
if(j<0) {
sort(num.begin(),num.end());
return;
}
int i=j+1;
while(i<n && num[i]>num[j]) i++;
i--;
swap(num[i],num[j]);
sort(num.begin()+j+1, num.end());
}
};
class Solution {
public:
void prevPermutation(vector<int> &num) {
if(num.size()<2) return;
int n = num.size(), j = n-2;
//find end of uptrend sequence
while(j>=0 && num[j]<=num[j+1]) j--;
if(j<0) {
sort(num.begin(),num.end());
return;
}
int i=j+1;
while(i<n && num[i]<num[j]) i++;
i--;
swap(num[i],num[j]);
sort(num.begin()+j+1, num.end(),greater<int>());
}
};