鱼儿慢慢游~~

导航

 

题目描述:

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

解释: 求下一个全排列。 认为全排列是按顺序依次排列,比如, 1, 2, 3 -》 1, 3, 2 -》 2, 1, 3 ,对于求全排列的问题,可以采用回溯法求解(注,面试时问道了这个问题,然后被灭了~)回溯法如图:

具体的回溯法求全排列,接下来再讲。这里继续讲下一个全排列的问题。

如上图, 对于1,3, 2来说,下一个全排列的求解,回溯至1,3,? 发现只有1,3, 2一种选择, 继续回溯至1,??,对于1,2 ? 一定是其前一个,而不是下一个,因此继续回溯,至 2,?,? 的第一个即 2, 1,3.

 

参考网上算法如下:

1. 从右往左,找到第一个非递增index的位置。如,1,3, 2 则找到 1.  如 7, 8, 6 ,9, 8, 7, 2 则找到 pos[2] = 6 

2. 从右往左,找到第一个大于pos[index] 的数,1, 3, 2 即 为2.   7,8,6,9,8,7,2 即为 pos[5] = 7

3. 交换 index 和步骤2 找到的数。 1,3,2 -> 2, 3,1      7,8,6,9,8,7,2 -> 7,8,7,9,8,6,2

4. 将index后面的数据,翻转。 2,3,1-> 2, 1, 3     7,8,7,9,8,6,2-> 7,8,7,2, 6, 8, 9

即得到所需答案。代码如下:

class Solution(object):
    def nextPermutation(self, nums):
        """
        :type nums: List[int]
        :rtype: void Do not return anything, modify nums in-place instead.
        """
        le = len(nums)
        index = -1
        
        for i in range(le-1, 0, -1):
            if nums[i] <= nums[i-1]:
                pass
            else:
                index = i-1
                break
        if index != -1:
            for i in range(le-1, index, -1):
                if nums[i] > nums[index]:
                    nums[i], nums[index] = nums[index], nums[i]
                    break
        i = index+1
        j = le-1
        while (i <= j):
            nums[i], nums[j] = nums[j], nums[i]
            i = i + 1
            j = j - 1
        

 

posted on 2016-05-25 10:22  miss_UU  阅读(154)  评论(0编辑  收藏  举报