【LeetCode】 31. Next Permutation

来源:互联网 发布:淘宝品质退款率怎么降 编辑:程序博客网 时间:2024/06/05 19:22

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

题意:
实现“下一个排列”函数,将排列中的数字重新排列成字典序中的下一个更大的排列。如果这样的重新排列是不可能的,它必须重新排列为可能的最低顺序(即升序排序)。重排必须在原地,不分配额外的内存。

解答

考虑序列4,3,2,1,显然对于此序列中并不存在比其更大的,因为此序列中是降序排列的,是此数字全排列的最大值。

考虑6 2 4 8 7 5 1,其下一个序列应该是6 2 5 1 4 7 8

其步骤应该如下:
1. n>0且n

class Solution {public:    void nextPermutation(vector<int>& nums) {        int n = nums.size()-1;        int left,right;        //步骤1:寻找 nums[n-1] >= nums[n]        while(n > 0 && nums[n-1] >= nums[n])            --n;        if(n>0)        {            int index = n-1;            //步骤2:n-1是大于nums[index]的最小值            while(n < nums.size() && nums[index] < nums[n])                ++n;            //步骤3:交换            swap(nums[index],nums[n-1]);            left = index+1;        }else   left = 0;        right = nums.size()-1;        while(left < right)            swap(nums[left++],nums[right--]);        return;    }};
原创粉丝点击