#leetcode's way to brush questions 31 - next permutation

Keywords: C++

To achieve the function of getting the next permutation, the algorithm needs to rearrange the given number sequence into the next larger permutation in the dictionary order.
If the next larger arrangement does not exist, rearrange the numbers into the smallest (i.e., ascending) arrangement.
It must be modified in place and only additional constant spaces are allowed.

Here are some examples where the input is in the left column and the corresponding output is in the right column.
1,2,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1

 

Ideas: 1. Try to traverse once to solve the problem. Traverse the array from the back to the front. If the latter is always larger than the former, then the array is the largest. In this case, you need to reverse the array.

2. If a number smaller than the previous one is found in the traversal process, and the position is i (at this time, the number behind i is arranged in descending order, which is the maximum value), then reverse the traversal, find the last number larger than this number in the later part, and exchange two numbers (at this time, the number behind i is arranged in descending order, but smaller than the previous one). At this time, the number behind i is still arranged in descending order , is the maximum value, but what we want is the next larger permutation, so we need to reverse the number after i. Namely: small + maximum arrangement -- > large + minimum arrangement

 

#include <iostream>
#include <vector>

using  namespace std;

void reverse(int begin,int end,vector<int>& nums)//Used to reverse sequence
{
    while(begin<end)
    {
        int temp=nums[begin];
        nums[begin]=nums[end];
        nums[end]=temp;
        begin++;
        end--;
    }
}


void nextPermutation(vector<int>& nums) {
    int i;
    int len=nums.size();
    if(len==0||len==1) return;
    if(len==2) {reverse(0,1,nums);
        return;}
    for(i=len-2;i>=0;i--)
    {
        if(nums[i]>=nums[i+1]) continue;
        else break;
    }
    if(i==-1) reverse(0,len-1,nums);
        //i Record where to swap
    else
    {
        for(int j=len-1;j>=i+1;j--)
        {
            if(nums[j]>nums[i])
            {
                int t=nums[j];
                nums[j]=nums[i];
                nums[i]=t;
                reverse(i+1,len-1,nums);
                break;
            }
        }
    }
}

int main() {
    vector<int> a={1,3,2};
    nextPermutation(a);
    std::cout <<a[0] <<a[1]<<a[2]<< std::endl;
    return 0;
}

Posted by Renich on Sat, 07 Dec 2019 06:32:04 -0800