leetcode第31题——next permutation(超过100%的解法)

问题描述
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
解法思路
怎么找到字典次序下的下一个序列。字典次序前面的数所占的比重比后面大。因此找最近的从右端项找起。找到最右边的位置,该位置后存在比该位置元素更大的数,交换两数(另一个数为更右边的比该位置数更大的数中最小的)的位置,该位置以后的元素按照升序排列。
C++代码

class Solution {
public:
    void nextPermutation(vector<int>& nums) {
        int n=nums.size();
        vector<int> dp(n,-1);
        int left=-1;//代表位置交换的左端数位置
        for(int i=n-2;i>=0;--i)
        {
            int flag=INT_MAX;
            for(int j=i+1;j<n;++j)
            {
                if(nums[j]>nums[i])
                {
                    if(nums[j]<flag)
                    {
                        dp[i]=j;
                        flag=nums[j];
                    }
                }
            }
            if(dp[i]!=-1)
            {
                int a=nums[i];
                nums[i]=nums[dp[i]];
                nums[dp[i]]=a;
                left=i;
                break;
            }
        }
        if(left!=-1)//将left后面的元素按照升序排列,采用冒泡排序
        {
            for(int i=left+1;i<n-1;++i)
            {
                for(int j=left+1;j<n-i+left;++j)
                {
                    if(nums[j]>nums[j+1])
                    {
                        int a=nums[j];
                        nums[j]=nums[j+1];
                        nums[j+1]=a;
                    }
                }
            }
        }
        else
        {
            sort(nums.begin(),nums.end());
        }
    }
};

算法结果
Runtime: 8 ms, faster than 100.00% of C++ online submissions for Next Permutation.
Memory Usage: 8.7 MB, less than 100.00% of C++ online submissions for Next Permutation.

猜你喜欢

转载自blog.csdn.net/weixin_43487878/article/details/89197751