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
解法一
例子:
1 2 7 4 3 1
1 2 7 4 3 1
1 3 7 4 2 1
1 3 1 2 4 7
先从后往前找到一个升序的位置(2),再从后往前找到比2大的数字,交换两个数字。然后再把当前3后面的数组反转。class Solution {
public:
void nextPermutation(vector<int>& nums) {
if(nums.size()<=1) return;
int len = nums.size();
for(int i=len-1; i>0; i--){
if(nums[i]>nums[i-1]){
int t = nums[i-1];
for(int j=len-1; j>=i; j--){
if(nums[j]>t){
swap(nums[j],nums[i-1]);
break;
}
}
reverse(nums.begin()+i,nums.end());
return;
}
}
reverse(nums.begin(), nums.end());
}
};