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 ;
}
};
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。