Type:medium
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 and use only constant 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,3,2,4为例:
1、从后往前读取数值。当第一次遇到数值变小时停止。即4-2为升序,记录2。
2、从后往前找最小的比2大的数,即4。
3、交换2、4的位置,变为1,3,4,2。
4、逆转4之后的数值。变为1,3,4,2。(这个例子中没变)。
然后就可以写代码了。
class Solution {
public:
void nextPermutation(vector<int>& nums) {
int n = nums.size();
if(n == 0 || n == 1) return;
int tt = 0;
for(int i=n-1; i>0; i--){
if(nums[i] > nums[i-1]){
tt = i-1;
break;
}
}
if(tt == 0 && nums[0]>nums[1]){
reverse(nums.begin(), nums.end());
return;
}
int min = INT_MAX;
int t = n-1;
for(int i=n-1; i>tt; i--){
if(nums[i] - nums[tt] < min && nums[i] - nums[tt] > 0){
t = i;
min = nums[i] - nums[tt];
}
}
swap(nums[tt], nums[t]);
reverse(nums.begin()+tt+1, nums.end());
return;
}
};