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
题目意思很好理解,就是找到一个序列关于字典序的下一个序列。
没有想到特别好的方法,就是单纯模拟人的判决过程,自己用1234把字典序排一遍就能找到规律,仔细思考自己为什么要做出这个判决,人脑是很优秀的,能够下意识地做出判断,可能你自己都没反应过来,所以慢一点好好思考才能跟上你大脑的判断。最后得到的规律大概就是先把大小关系确定,然后从末尾开始找,找到第一个大于符号,记录下位置,将序列分成两部分
eg:1<3>4<2,第一个大于为3>4,记录下3和4的位置,这样将序列分为1,3和4,2两个部分,设置两个指针i,j分别在子序列的末尾,嵌套循环遍历两个子序列,前面的子序列在外层循环,找到指针对应的数也是大于,这样从i到末尾这个子序列的下一个字典序就是以nums【j】作为第一位,剩下的从小到大排序就好了。有点递归的意思,找到一个最短子序列,只要将这个子序列的下一个字典序找到就找到了整个序列的下一个字典序。
代码如下:
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
class Solution {
public:
static void nextPermutation(vector<int>& nums) {
int l=nums.size()-1;
int left=-1,right=-1;
for(int i=l;i>0;i--)
{
if(nums[i]>nums[i-1])
{
left=i-1;
right=i;
break;
}
}
//cout<<left<<" "<<right<<endl;
int flag=false;
if(left==-1)
right=0;
else
for(int j=left;j>=0;j--)
{
for(int i=l;i>=right;i--)
{
if(nums[i]>nums[j])
{
swap(nums[i],nums[j]);
flag=true;
break;
}
}
if(flag)
break;
}
cout<<"aaa"<<endl;
sort(nums.begin()+right,nums.end());
}
};
int main()//测试部分
{
int a[]={4,2,0,2,3,2,0};
vector<int> b(a,a+sizeof(a)/sizeof(int));
Solution::nextPermutation(b);
for(int i=0;i<b.size();i++)
cout<<b[i]<<" ";
}