LeetCode—31. Next Permutation

Type:medium

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 and use only constant 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,3,2,4为例:

1、从后往前读取数值。当第一次遇到数值变小时停止。即4-2为升序,记录2。

2、从后往前找最小的比2大的数,即4。

3、交换2、4的位置,变为1,3,4,2。

4、逆转4之后的数值。变为1,3,4,2。(这个例子中没变)。

然后就可以写代码了。


class Solution {

public:

    void nextPermutation(vector<int>& nums) {

        int n = nums.size();

        if(n == 0 || n == 1) return;

        int tt = 0;

        for(int i=n-1; i>0; i--){

            if(nums[i] > nums[i-1]){

                tt = i-1;

                break;

            }

        }

        if(tt == 0 && nums[0]>nums[1]){

            reverse(nums.begin(), nums.end());

            return;

        }

        int min = INT_MAX;

        int t = n-1;

        for(int i=n-1; i>tt; i--){

            if(nums[i] - nums[tt] < min && nums[i] - nums[tt] > 0){

                t = i;

                min = nums[i] - nums[tt];

            }

        }

        swap(nums[tt], nums[t]);

        reverse(nums.begin()+tt+1, nums.end());

        return;

    }

};

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

友情链接更多精彩内容