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
这题完全没看懂, 百度了好多才弄明白基本题意,大概说一下我的理解,从后向前遍历,找到第一个打破递减顺序的数字的坐标。然后找出来已经遍历过的序列里中比这个数字大但还是其中最小的数字。
说的也是云里雾里,这题出的不咋好我觉得。。。哈哈哈
不知道到底要干点啥。。
class Solution {
public:
void nextPermutation(vector<int>& nums) {
int index=nums.size()-1;
while(nums[index]<=nums[index-1])
{
index--;
}
if(index==0)
{
sort(nums.begin(),nums.end());
return;
}
int min=INT_MAX;
int mindex=INT_MAX;
for(int i=index;i<=nums.size()-1;i++)
{
if(nums[i]>nums[index-1])
{
if(nums[i]<min)
{
min=nums[i];
mindex=i;
}
}
}
int temp=nums[index-1];
nums[index-1]=nums[mindex];
nums[mindex]=temp;
sort(nums.begin()+index,nums.end());
}
};