[Leetcode 52] Next Permutation report

Source: Internet
Author: User

Question:

Given a list of integers, which denote a permutation.

Find the next permutation in ascending order.

Example

[1,3,2,3]for, the next permutation is[1,3,3,2]

[4,3,2,1]for, the next permutation is[1,2,3,4]

Note

The list may contains duplicate integers.

What is Next permutation?

The permutation with current charactors, which is lexicographically next.

1234-1243
4321-1234
1243-1324
2134-2143

Idea:

Answer:

 classSolution {  Public:     /** * @param nums:an array of integers * @return: An array of integers that ' s next permuation      */vector<int> Nextpermutation (vector<int> &nums) {         //Write your code here         if(Nums.size () <=1) {             returnnums;         }                  //Find first element is smaller that next element         intFirst_small_index =-1;          for(inti = nums.size ()-2; I >=0; --i) {             if(Nums[i] < nums[i+1]) {First_small_index =i;                  Break;             }         }         //find the first element is just bigger than the element we found         if(First_small_index! =-1) {             intFirst_bigger_index =First_small_index;              for(inti = First_small_index +1; I < nums.size (); ++i) {                 if(Nums[i] >Nums[first_small_index]) {First_bigger_index =i;}Else {                      Break;                 }             } swap (Nums[first_small_index], Nums[first_bigger_index]);         }         //Reverse Rest ArrayReverse (Nums.begin () + First_small_index +1, Nums.end ());                  returnnums;     }};

[Leetcode 52] Next Permutation report

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.