Next Permutation
问题描述:
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
知识补充:
测试代码:
void nextPermutation(vector<int>& nums) {
int i=nums.size()-1;
for(;i>0;i--)
{
if(nums[i]>nums[i-1])
{
int j = i,min_pos=i;
while(j<nums.size())
{
if(nums[j]<nums[min_pos]&&nums[j]>nums[i-1])
min_pos = j;
j++;
}
swap(nums[i-1],nums[min_pos]);
sort(nums.begin()+i,nums.end());
break;
}
}
if(i==0)
{
reverse(nums.begin(),nums.end());
}
}
性能:
参考答案:
class Solution {
public:
void nextPermutation(vector<int>& nums) {
int sz = nums.size(),i = sz-1;
while(i > 0){
if(nums[i-1] < nums[i])
break;
i--;
}
i--;
if(i >= 0){
int j = sz-1;
while(j >= 0){
if(nums[j] > nums[i])
break;
j--;
}
swap(nums[i],nums[j]);
}
reverse(nums.begin()+(i+1),nums.end());
}
};