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