leetcode:31. Next Permutation 下一个排列

来源:互联网 发布:中国历届人口普查数据 编辑:程序博客网 时间:2024/05/12 06:19

31. 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

思路

  • 这是一道全排列的题,思路可参考31 Next Permutation
  • 如果不熟悉原理,非常容易绕晕
  • 采用从尾部往前遍历的方式
  • 关键是从后往前遍历,找到破坏升序排列的位置,然后交换位置后,对后面的数据进行重新排序。

算法步骤

输入: 一个排列nums
输出:下一个排列
1. 判断nums是否为空,为空则返回
2. 设nums的长度为m。外循环从倒数第2个开始往前遍历:i
1. 内循环从倒数第1个开始往前遍历,直到i+1:j
1. 如果i+1到m的数中有大于第i个数,则在满足该条件的数集中找到最小的值min,并记录位置为k。
2. 如果位置k存在,则交换第i个数和第k个数,并且对i+1到m个数进行升序排列
3. 返回下一个排列nums。

代码

bool Solution::nextPermutation2(vector<int>& nums){    if(nums.size()==0)        return false;    for(int i=nums.size()-2;i>=0;i--)    {        int min=INT_MAX;        int k=-1;        for(int j=nums.size()-1;j>i;j--)        {            if(nums[i]<nums[j] && nums[j]< min)            {                k=j;                min=nums[j];            }        }        if(k != -1)        {            int temp=nums[k];            nums[k]=nums[i];            nums[i]=temp;            sort(nums.begin()+i+1,nums.end());            return false;        }    }    // 如果是最大时    for(int i=0;i<nums.size()/2;i++)    {        int temp=nums[i];        nums[i]=nums[nums.size()-i-1];        nums[nums.size()-i-1]=temp;    }    return true;}
0 0
原创粉丝点击