题目链接:https://leetcode.com/problems/next-permutation/
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
思路:求下一个字典序有个规则。比如1,2,3,4,5,6这六个数的的第一个字典序是递增排列的1,2,3,4,5,6,最后一个排列是逆序排列的6,5,4,3,2,1。
举个栗子:6,3,5,4,2,1,要找这个数的下一个字典序,有下列步骤完成:
1. 从右往左找到第一个比右边数小的数3
2. 然后从这个数右边5开始往右找最后一个比3大的数4
3. 交换这两个值,则现在数组变成6,4,5,3,2,1
4. 现在将4后面的数排列成递增序列,即将其就地逆序,之后的数组将变成6,4,1,2,3,5,这个序列就是我们要求的下一个字典序。
代码如下:
class Solution {
public:
void nextPermutation(vector<int>& nums) {
int len = nums.size(), i = len -1;
if(len == 0) return;
while(i > 0 && nums[i-1] >= nums[i])//找到第一个比右边小的数
i--;
if(i == 0)//完全逆序则就地逆置
{
reverse(nums.begin(), nums.end());
return;
}
int left = i-1;
while(i < len && nums[i] > nums[left])//找到最后一个比left值大的数
i++;
swap(nums[i-1], nums[left]);
i = left +1;
reverse(nums.begin()+i, nums.end());//就地逆置后面的数组
}
};