leetcode:permutation系列

一、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)]);
        } } }

 

posted @ 2017-05-20 10:21  糯米米一粒  阅读(130)  评论(0编辑  收藏  举报