zoukankan      html  css  js  c++  java
  • 【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
  • 相关阅读:
    centos6下安装部署hadoop2.2
    centos 卸载自带的 java
    完全分布式Hadoop2.3安装与配置
    hadoop安装与WordCount例子
    CentOS 6.5 下载地址
    碎片化
    DRM加密技术是怎么一回事
    DRM你又赢了:其API纳入HTML5标准
    java 对视频和图片进行加密解密
    HadoopDB:混合分布式系统
  • 原文地址:https://www.cnblogs.com/seyjs/p/5333210.html
Copyright © 2011-2022 走看看