Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.
If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).
The replacement must be in-place, do not allocate extra memory.
Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.
1,2,3
→ 1,3,2
3,2,1
→ 1,2,3
1,1,5
→ 1,5,1
class Solution { public: void nextPermutation(vector<int> &num) { // Note: The Solution object is instantiated only once and is reused by each test case. for(int i=num.size()-2;i>=0;i--){ if(num[i]<num[i+1]){ //from i to end //eg. 1243 //first find 243 then find the next value bigger than 2,swap it with 2 and sort then we get 324 vector<int> one; int ptr=i+1; for(int j=i+2;j<num.size();j++){ if(num[j]>num[i]&&num[j]<num[ptr]){ ptr=j; } } int temp=num[i]; num[i]=num[ptr]; num[ptr]=temp; for(int j=i+1;j<num.size();j++) one.push_back(num[j]); sort(one.begin(),one.end()); for(int j=0;j<one.size();j++){ num[i+1+j]=one[j]; } return; } } sort(num.begin(),num.end()); } };