题目:
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
分析:
题目的意思实际上是:除非输入数组为递减数组,否则就是把该数组代表的数字“变大”,且变大的值尽可能小。变大意味着数组肯定有某一个下标的值从小变成大。这个下标通过找规律,发现是 “步骤2” 中提到的i-1。找到这个下标后,便在其后面的数里找一个比nums[i-1]大的最小的数nums[index],交换nums[i-1]和nums[index]的值,然后把下标[i,size-1]内的数从小到大排序。
步骤:
1、若输入数组为递减数组,则从小到大排序后输出。
2、从后往前找到第一个下标i,使得nums[i]>nums[i-1],在下标[i,size-1]中找到比nums[i-1]大的最小的数nums[index],交换nums[i-1]和nums[index]的值,然后把下标[i,size-1]内的数从小到大排序。
class Solution {
public:
void nextPermutation(vector<int>& nums) {
int size=nums.size();
if(size<=1)
return;
int i=size-1;
for(;i>=1;--i)
{
if(nums[i]>nums[i-1])
break;
}
if(i==0)
{
sort(nums.begin(),nums.end());
return;
}
int index=i;
for(int j=index+1;j<size;++j)
{
if(nums[j]>nums[i-1] && nums[index]>nums[j])
index=j;
}
swap(nums[index],nums[i-1]);
sort(nums.begin()+i,nums.end());
}
};