[Leetcode] Next permutation

Source: Internet
Author: User

Next permutation

Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.

If Such arrangement is not a possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).

The replacement must is in-place, do not allocate extra memory.

Here is some examples. Inputs is in the left-hand column and its corresponding outputs is in the right-hand column.
1,2,31,3,2
3,2,11,2,3
1,1,51,5,1

Problem Solving Ideas:

This is an algorithmic problem. Learned a new way. Happy. The solution is as follows:


Class Solution {Public:void nextpermutation (vector<int> &num) {int len = num.size ();        if (len<2) {return;        }//int target1=-1 from right to left in the first reverse order;                for (int i=len-2; i>=0; i--) {if (num[i]<num[i+1]) {target1=i;            Break            }} if (target1>=0) {int target2=-1;                    for (int i=len-1; i>target1; i--) {if (Num[i]>num[target1]) {target2=i;                Break        }} swap (num, target1, Target2);    } reverse (num, target1+1, len-1);        } void Swap (vector<int>& num, int i, int j) {int temp=num[i];        NUM[I]=NUM[J];    Num[j]=temp;            } void reverse (vector<int>& num, int i, int j) {while (i<j) {swap (num, I, j);            i++;        j--; }    }};


[Leetcode] Next permutation

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.