1. 程式人生 > >leetcode:permutation系列

leetcode:permutation系列

sub some 如果 位置 遞增 需要 個數 all column

一、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,31,3,2
3,2,11,2,3
1,1,51,5,1

看到此題,有點摸不著頭腦,但是稍作分析,發現是有規律的。思路分析如下

其實給定一串數字,其排列:a0,a1,a2,……,an-2,an-1,總存在這樣三種情況:

①、這個降序排列: a0>a1>a2>……>an-2>an-1 顯然,就是最大的一個排列序列,下一個不前後元素翻轉排列成為最小的一個排列;

②、前面無所謂,最後面是升序排列: ……<an-2<an-1 這個只需要最後這兩個元素交換位置就可以了,即成下一個排列;

③、前面有升序,最後面是降序排列: ……ai-1<ai>ai+1>……>an-2>an-1 這種情況需要首先找到從ai開始最小的大於ai-1的數於ai-1交換,然後把ai到an-1 翻轉
成遞增序列。

實現代碼:

void nextPermutation(vector<int
>& nums) { if(nums.size() <= 1) return ; int len=nums.size(); int i=len-1; while(i>0 && nums[i]<=nums[i-1]) --i; if(i==0) { for(int j=0;j<len/2;++j) swap(nums[j], nums[len-1-j]); } else if(i==len-1) swap(nums[i],nums[i-1]); else { int index=i; while(index<len && nums[index]>nums[i-1]) ++index; --index; swap(nums[i-1],nums[index]); for(int j=i;j<i+(len-i)/2;++j) swap(nums[j], nums[len-1-(j-i)]); } }

leetcode:permutation系列