Leetcode: Next Permutation, space

Source: Internet
Author: User

Leetcode: Next Permutation, space

I. Question

This question provides a series of minimum numbers greater than this series.

For example:

1, 2, 3 → 1, 3, 2

3, 2, 1 → 1, 2, 3

1, 1, 5 → 1, 5, 1

Ii. Analysis

C ++-loving shoes may immediately think of the library function next_permutation (). That's right. In fact, this question is actually implemented (strictly speaking, it is only a preliminary implementation). If yes, if you directly enter this line of code, you can use:

 

void nextPermutation(vector<int> &num) {       next_permutation( num.begin(), num.end() );}

However, it's not that we have ended like this. Of course we can't. We have to implement it ourselves. When we observe the sequence, we will find that if the sequence is decreasing, we cannot find a sequence that is larger than it, so we need to find two incrementing elements, that is, from right to left, find the first element on the left that is less than the right, and then find the smallest element on the right that is greater than the right of the element, swap two numbers, then, reverse () is followed by the number.

There are four steps:

1. from right to left, find the first element num [I] on the left that is less than the right.

2. Find the first element num [j] greater than num [I] from right to left.

3. Exchange num [I] And num [j];

4. reverse () after num [I ()

The Code is as follows:

 

class Solution {public:    void nextPermutation(vector<int> &num) {        int len = num.size()-1;        int count = len-2;        int i,j;        for(i=len-1; i>=0; i--){        if(num[i+1]>num[i]){        for(j=len; j>i-1; j--){        if(num[j]>num[i])        break;        }        swap(num[i],num[j]);        reverse(num.begin()+i+1,num.end());        return;        }        }        reverse(num.begin(),num.end());        return;    }        void swap(int &a, int &b){    a = a + b;b = a - b;a = a - b;     }};


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.