Next Permutation

来源:互联网 发布:大米评测淘宝店 编辑:程序博客网 时间:2024/06/07 19:05

题目: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

思路:主要就是找出仅大于原排列的下一排列,如果原排列是最大排列,就返回最小排列。所以我们先试着从后往前寻找一个能替换增大的最低位,然后把排序的index(初始化为0)设为这一位的下一位。最后对从排序index开始的所有数字从小到大排序就行。


伪代码:不怎么会写,后面再发把。

具体代码:

void nextPermutation(vector<int>& nums) {    int lens = nums.size();    int minIndex = 0;    int temp = 0;    for (int i = lens - 2; i>=0; i--)    {        for (int j = lens-1; j>i; j--)        {            if (nums[j]>nums[i])            {                temp = nums[i];                nums[i] = nums[j];                nums[j] = temp;                minIndex = i + 1;                break;            }        }        if (minIndex)        {            break;        }    }    for (int i = minIndex; i<lens; i++)    {        for (int j = i+1; j < lens; j++)        {            if (nums[j] < nums[i])            {                temp = nums[j];                nums[j] = nums[i];                nums[i] = temp;            }        }    }}


0 0