【leetcode】Permutations

 Given a collection of distinct numbers, return all possible permutations.

For example,
[1,2,3] have the following permutations:
[1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], and [3,2,1]. 

这是一个全排列的问题。

关于全排列,网上有很多解法。

其中一个解法,我觉得比较简单,于是就用这个解法来试下。

【例】 如何得到346987521的下一个
    1,从尾部往前找第一个P(i-1) < P(i)的位置
            3 4 6 <- 9 <- 8 <- 7 <- 5 <- 2 <- 1
        最终找到6是第一个变小的数字,记录下6的位置i-1
    2,从i位置往后找到最后一个大于6的数
            3 4 6 -> 9 -> 8 -> 7 5 2 1
        最终找到7的位置,记录位置为m
    3,交换位置i-1和m的值
            3 4 7 9 8 6 5 2 1
    4,倒序i位置后的所有数据
            3 4 7 1 2 5 6 8 9
    则347125689为346987521的下一个排列

 

代码如下:

def permute(self,nums):
        nums.sort()
        length = len(nums)
        if length == 1:
            return [nums]
        start = 0
        startValue = 0
        last = 0
        count = reduce(lambda x,y:x*y,range(1,length+1))
        res = []
        print( count)
        while count:
            res.append(copy.copy(nums))
            for i in range(length-1,0,-1):
                if nums[i] > nums[i-1]:
                    start = i
                    startValue = nums[i-1]
                    break
            for i in range(i,length):
                if nums[i] > startValue:
                    last = i
            #swap
            temp = nums[start-1]
            nums[start-1] = nums[last]
            nums[last] = temp

            tl = nums[start:length]
            nums = nums[0:start]
            tl.reverse()
            nums+=tl
            count -=1
        return res

 

posted @ 2016-03-29 15:42  seyjs  阅读(201)  评论(0编辑  收藏  举报