leetcode31---Next Permutation

来源:互联网 发布:枪林弹雨刷枪软件下载 编辑:程序博客网 时间:2024/06/05 08:34

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,23,2,1 → 1,2,31,1,5 → 1,5,1

也就是说,给你一个排列,输出字典序中的下一个排列。比如123生成的全排列是:123,132,213,231,312,321。那么132的next permutation是213;321的next permutation是123。

代码:

思想:字典序的第一个一定是完全升序的排列,最后一个一定是完全降序的排列。因此寻找下一个排列的过程就是:
(1)i从倒数第二个数开始,从后往前寻找到第一对满足升序排列的数,将其变为降序。也就是找到第一个满足nums[i] < nums[i+1]的数。如123下一个为132:从后往前遍历123,找到23,将其变为32.
(2)如果前面找到的i为-1,说明整个序列已经完全降序,其下一个就是直接将其逆序;否则,从倒数第一个数开始,从后往前寻找第一个比num[i]大的数对应下标j。
(3)swap(nums[i], nums[j]);
(4)将下标i之后的所有元素逆序

4个重要步骤已在代码注明

#include <iostream>#include<vector>#include<algorithm>using namespace std;class Solution {public:    void nextPermutation(vector<int>& nums) {        int n=nums.size();        if(n<=1) return;        int i;        //例如(1) |13|2 找到i=0-->(2) 找到从后往前第一个比nums[0]大的数2 -->(3) 交换1和2的位置231 -->(4)213        for(i=n-2;i>=0;i--)//自倒数第二个开始,从后往前遍历        {            if(nums[i+1]>nums[i]) break;//(1)找到第一个满足nums[i] < nums[i+1]的i        }        if(i==-1)//说明nums中的数全是递减排列,nums为字典最大排列        {//其下一个就是最小排列,即nums的完全逆序            reverse(nums.begin(), nums.end());            return;        }        int j;        for(j=n-1;j>i;j--)        {//(2)//从右至左找到第一个比num[i]大的就是数nums[j]            if(nums[j]>nums[i]) break;        }        swap(nums[i],nums[j]);//(3)交换nums[i]和nums[j]        reverse(nums.begin()+i+1, nums.end());//(4)将nums[i+1]至结尾的元素逆序    }};int main(){    Solution s;    vector<int> nums={1,3,2};    s.nextPermutation(nums);    for(int i=0;i<nums.size();i++)    {        cout<<nums[i]<<" ";    }    cout<<endl;    return 0;}
0 0
原创粉丝点击