Next Permutation--leetcode

Source: Internet
Author: User

Mplement 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

Using the idea of STL, from the next to find a pair of adjacent number, in a pair of adjacent number of the first element is less than the second element, remember to do *i<*ii, from the back to find the first element *j, yes *j>*i, then Exchange *i and *j, and then Exchange from *II start (contains * ii) to the sequence at the end of the array.

void Rserve (vector<int>& vec,int begin,int end)  {while      (begin <= End)      {          swap (Vec[begin] , Vec[end]);          begin++;          end--;      }  }     BOOL Findpair (vector<int>& vec,int& first,int& second)  {      int last = Vec.size ()-1;      for (; last>0;last--)      {          second = last;          first = last-1;          if (Vec[first] < Vec[second])              return true;      return false;  }    void Nextpermutation (vector<int>& vec)  {      int first,second,index;      if (Findpair (Vec,first,second))      {          index = vec.size ()-1;          for (; index>=first;index--)          {              if (Vec[index] > Vec[first]) break                  ;          }          Swap (Vec[index],vec[first]);          Rserve (Vec,second,vec.size ()-1);       }  


Next Permutation--leetcode

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.