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]<<" ";
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章