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,3→1,3,2
3,2,1→1,2,3
1,1,5→1,5,1
Test instructions: Find a larger sequence than the sequence, and the last one is back to the smallest.
Thought: The same thing done before: the solution
Class Solution {public: void Nextpermutation (vector<int> &num) { if (num.size () < 2) return; int i = Num.size ()-2; while (Num[i] >= num[i+1] && i! =-1) i--; if (I < 0) { reverse (num.begin (), Num.end ()); return; } Int J = num.size ()-1; while (Num[j] <= num[i]) j--; Swap (Num[i], num[j]); Reverse (Num.begin () + i + 1, num.end ());} };
Leetcode Next permutation