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:
/*algorithm:
get one descending order sublist[l,r]
from l,r,select first one A[k] bigger than A[l-1]
swap A[k] and A[l-1] and reverse sublist[l,r]
if l = 0,reverse whole list
time O(n) space O(1)
*/
void nextPermutation(vector<int>& nums) {
int n = nums.size();
int l = n-1,r = n-1;
while(l && nums[l-1] >= nums[l])--l;
//in [l,r], search first element which bigger than l-1
if(l > 0){
int k;
for(k = r;k >= l && nums[k] <= nums[l-1];k--);
swap(nums[k],nums[l-1]);
}
reverse(nums.begin()+l,nums.end());
}
};