1. 题目
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
2. 思路
根据规则,从后往前找到第一个逆序点,然后从这个点开始后,找到最小的大于逆序点小值的数,二者兑换后,对后面的整体进行反转。
即a0a1a2...aN-1的数下,找到 a[i]<a[i+1] && a[i+1]>a[i+2]>....>a[N-1]。
然后找到a[j]>a[i] && a[j+1]<=a[i], 对调i,j后,a[i+1,....,N-1]形成非升序,翻转为非降序即可。
3. 代码
class Solution {
public:
void nextPermutation(vector<int>& nums) {
// 从末尾开始, 找到第一个逆序点i, 即a[i] < a[i+1] && a[i+1] >= a[i+2] >= ... >= a[N-1]
// 在[i+1, N-1]范围内找到最小的比a[i]大的数a[j]; i,j 对调后,对[i+1, N-1]进行反转
if (nums.size() < 2) return ;
int i = nums.size() - 2;
for (; i >= 0; i--) {
if (nums[i] < nums[i+1]) {
break;
}
}
if (i < 0) {
sort(nums.begin(), nums.end());
return ;
}
int j = i + 1;
int ni = nums[i];
for (; j < nums.size(); j++) {
if (nums[j] <= ni) {
break;
}
}
j--;
nums[i] = nums[j];
nums[j] = ni;
std::reverse(nums.begin()+i+1, nums.end());
return ;
}
};
内容来源:https://segmentfault.com/a/1190000007285442
参考http://blog.csdn.net/sunshine0_0/article/details/53222575
二、解题思路:
题目的意思是:给定一个数字排列,让你输出下一个比这个数字排列大的数字排列,即最小的比给定数字大的数字排列。若没有,把数组从小到大排序。
1、首先,我们考虑给定一个数字排列,是否有比它更大的排列(即若排列为逆序就没有更大的排列了)?这是第一步,判断的方法是,从后往前遍历数组,判断后一位是否比前一位小,一旦遇到不是的,那么就必定存在比给定排列更大的排列(此时跳出循环,并记下此时循环变量flag,方便后面使用);否则,不存在更大的。
2、若不存在更大的,那把数组逆序一下即可。
3、若存在,说明要构造一个更大的排列了,在第一步我们记下的循环变量值flag,即是要进行改变的位置。此时循环检测flag后面的值,找到最小的比flag位置的值大的值的位置(好绕呦,结合代码看看喽),交换这两个值,然后把flag之后的值按升序排列即可。
ps:我要说,我的英语真是有够烂的,每次都看不懂题,所以单词还是要接着好好背!
三、源码: