【LeetCode】31. 下一个排列

链接:

https://leetcode-cn.com/problems/next-permutation

描述:

实现获取下一个排列的函数,算法需要将给定数字序列重新排列成字典序中下一个更大的排列。
如果不存在下一个更大的排列,则将数字重新排列成最小的排列(即升序排列)。
必须原地修改,只允许使用额外常数空间。

以下是一些例子,输入位于左侧列,其相应输出位于右侧列。
1,2,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1

void nextPermutation(vector<int>& nums) {}

思路:

最直观的想法是,得到数组中元素的所有排列,并按字典序排序。
然后,就可以在其中找到当前排列的下一个更大的排列了。
但,这个方法太耗时耗力了。

下面,介绍如何从当前排列得到下一个更大的排列。
比如:[1,2,3,8,5,7,6,4]

为了得到更大的排列,需要将靠后的大数和靠前的小数交换,且尽可能交换靠后的数字
于是,从后往前看,
[...,4],[...,6,4],[...,7,6,4],
目前是从大到小排好序的,不能再变大了。
下一步,[...,5,7,6,4],出现了一个转折点。
需要将小数 5 和后面的大数交换,
找到尽可能靠后的且大于小数 5 的数字,也就是 6。
交换这两个数字,得到 [...,6,7,5,4]。
此时,排列已经变大了。
最后,将[...,7,5,4]变为最小的排列[...,4,5,7]。

C++

展开后查看
class Solution {
public:
    void nextPermutation(vector<int>& nums) {
        int small = nums.size() - 2;
        int big = nums.size() - 1;
        while(small >= 0 && nums[small] >= nums[small + 1]){
            small--;
        }
        if(small >= 0){
            while(nums[small] >= nums[big]){
                big--;
            }
            swap(nums, small, big);
        }
        reverse(nums, small + 1, nums.size() - 1);
    }
    void reverse(vector<int>& nums, int start, int end){
        while(start < end){
            swap(nums, start, end);
            start++;
            end--;
        }
    }

    void swap(vector<int>& nums, int i, int j){
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }
};

Java

展开后查看
class Solution {
    public void nextPermutation(int[] nums) {
        int small = nums.length - 2;
        int big = nums.length - 1;
        while(small >= 0 && nums[small] >= nums[small + 1]){
            small--;
        }
        if(small >= 0){
            while(nums[small] >= nums[big]){
                big--;
            }
            swap(nums, small, big);
        }
        reverse(nums, small + 1, nums.length - 1);
    }
    void reverse(int[] nums, int start, int end){
        while(start < end){
            swap(nums, start, end);
            start++;
            end--;
        }
    }
    void swap(int[] nums, int i, int j){
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }
}
posted @ 2020-06-24 12:14  CrazyBlogs  阅读(57)  评论(0编辑  收藏  举报