-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathNext Permutation.txt
56 lines (52 loc) · 1.39 KB
/
Next Permutation.txt
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
problem:
Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.
If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).
The replacement must be in-place, do not allocate extra memory.
Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.
1,2,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1
------------------------------------------------------------------------------
solution:
//1、从后往前找严格升序对,记索引分别为i, j,如果未找到跳第4步
//2、找到后将索引i,j下的值交换
//3、i后面也全部为降序,因此需将这部分全部reverse
//4、则整个序列都为降序,这个时候返回序列的升序,即把原序列reverse下
void swap(vector<int> &num, int l, int r)
{
int tmp = num[l];
num[l] = num[r];
num[r] = tmp;
}
void reverse(int start, int end, vector<int> &num)
{
while(start < end)
{
swap(num, start, end);
start++;
end--;
}
}
void nextPermutation(vector<int> &num)
{
if(num.size() <= 1)
return;
int l = num.size() - 2;
int r = num.size() - 1;
while(num[l] >= num[r])
{
if(l + 1 == r)
{
l--;
r = num.size() - 1;
if(l < 0)
break;
}
else
r--;
}
if(l >= 0)
swap(num, l, r);
reverse(l+1, num.size() - 1, num);
return;
}