【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 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,2,3的全排列为

1,2,3

1,3,2

2,1,3

2,3,1

3,1,2

3,2,1

题目给你一串数字,是这串数字全排列中的某一个排列,你要输出的是它的下一个排列,就是题目中给的例子。(这道题目说明看的我一脸懵逼,百度了一下才明白题目的意思)

思路:全排列有点递增排列的意思,我们可以把它看成一个数字,他们所在的位置对应百位十位个位。我们只需要找到当前数字下一个最小数字。

6 5 4 8 7 5 1的下一个排列是什么?

我们从后往前看,1<5<7<8,但是到了4我们发现8>4。我们想把排列往大的排列调,那么我们就应该把大的数字放在高位,所以4是下一个排列的关键位置。我们之前的序列1 5 7 8 中找到比4大但是在1 5 7 8中最小的数字,就是5了。下面我们交换他俩的位置:6558741,然后对8741做一个递增的排列:6551478,这就是我们要的结果。

代码:

class Solution {
public:
    void nextPermutation(vector<int>& nums) {
        int index=-1;
        for(int i=nums.size()-1;i>=1;i--){
            if(nums[i]>nums[i-1]){
                index = i-1;
                break;
            }    
        }
        if(index>=0){
            for(int i=nums.size()-1;i>=index+1;i--){
                if(nums[i]>nums[index]){
                    swap(nums[i],nums[index]);
                    break;
                }
                    
            }
            sort(nums.begin()+index+1,nums.end());
        }
        else{
            reverse(nums.begin(), nums.end());  
        } 
    }
};




猜你喜欢

转载自blog.csdn.net/poulang5786/article/details/80204513