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,3→
1,3,2
3,2,1→
1,2,3
1,1,5→1,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