NextPermutation
Updated:
/*
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
- */
类似STL 里的 next_permutation方法
- 首先,从最尾端开始往前寻找两个相邻的元素,令第一个元素是 i,第二个元素是 ii,且满足 i < ii ;
- 然后,再从最尾端开始往前搜索,找出第一个大于 i 的元素,设其为 j;
- 最后将 i 和 j 对调,再将 ii 及其后面的所有元素反转。
java: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
28public class NextPermutation {
public void nextPermutation(int[] num) {
for (int i = num.length - 2; i >= 0; i--) {
if (num[i] < num[i + 1]) {
for (int j = num.length - 1; j > i; j--) {
if (num[j] > num[i]) {
swap(num, i, j);
reverse(num, i + 1, num.length - 1);
return ;
}
}
}
}
reverse(num, 0, num.length - 1);
}
public void swap(int[] array, int i, int j) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
public void reverse(int[] array, int start, int end) {
for (int i = start; i <= (start + end) / 2; i++)
swap(array, i, start + end - i); // end - (i - start)
}
}
C++:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24class Solution {
public:
void nextPermutation(vector<int> &num) {
if (!num.size())
return;
int idx = num.size() - 2;
// 1. find out the last wrong order
while (idx >= 0 && num[idx] >= num[idx + 1])
idx--;
// 2. swap
if (idx >= 0) {
int i = idx + 1;
while (i < num.size() && num[i] > num[idx])
i++;
swap(num[i - 1], num[idx]);
}
// 3. reverse
reverse(num.begin() + idx + 1, num.end());
}
};