31. Next Permutation
Description
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 and use only constant 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: (Java)
class Solution {
public void nextPermutation(int[] nums) {
int swap_index = -1, temp;
for (int i = nums.length-2; i >= 0; i--) {
if (nums[i] < nums[i+1]) {
// 从右往左,找到第一个逆序的位置
swap_index = i;
for (int j = nums.length-1; j > swap_index; j--) {
if (nums[j] > nums[swap_index]) {
// 从右往左(也可以从左往右,找到最后一个比逆序位置数大的),找到第一个比逆序位置数大的,交换两者
temp = nums[swap_index];
nums[swap_index] = nums[j];
nums[j] = temp;
break;
}
}
break;
}
}
int left = swap_index+1;
int right = nums.length-1;
// 将后面的降序的数组翻转为升序
while (left < right) {
temp = nums[left];
nums[left] = nums[right];
nums[right] = temp;
left++;
right--;
}
}
}
思路
题意为找出一个数组全排列的下一个排列,举例:{1,2,3}的全排列为{123,132,213,231,312,321},那么123的下一个全排列为132,312的下一个全排列为321。解题流程如下:
- 从右往左,找到第一个逆序(减小)的位置(因为后面如果是降序的,那无论如何交换都不能比给出的全排列大)
- 从右往左(也可以从左往右,找到最后一个比逆序位置数大的),找到第一个比逆序位置数大的,交换两者
- 将后面的降序的数组翻转为升序(因为下一个排列需满足:比给出的全排列大且是最小的)
结合字典序全排列的特性就好理解了。