题目描述:
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
题意为找出某个数的全部数字的下一个排列,思路为从低位开始找出一个单增序列,从而确定第一个非单增数nums[pos1],并从单增序列中找出恰好比这个数大的最小数nums[pos2],将这两个数交换,并翻转pos1之后的所有数。注意当原数字已经为最大排列时,需要单独判断,直接翻转。
class Solution {
public:
void nextPermutation(vector<int>& nums) {
int pos1=0;
int pos2=0;
bool flag=true;
for(int i=nums.size()-2;i>=0;i--)
{
pos1=i;
if(nums[i]<nums[i+1])
{
flag=false;
break;
}
}
if(flag)
{
reverse(nums.begin(),nums.end());
return;
}
for(int i=pos1+1;i<nums.size();i++)
{
pos2=i;
if(i==(nums.size()-1)||nums[i+1]<=nums[pos1]) break;
}
swap(nums[pos1],nums[pos2]);
reverse(nums.begin()+pos1+1,nums.end());
}
};