leetcode 31. 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

题目意思很好理解,就是找到一个序列关于字典序的下一个序列。

没有想到特别好的方法,就是单纯模拟人的判决过程,自己用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]<<" ";
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值