• Permutation Sequence


    The set [1,2,3,…,n] contains a total of n! unique permutations.

    By listing and labeling all of the permutations in order,
    We get the following sequence (ie, for n = 3):

    1. "123"
    2. "132"
    3. "213"
    4. "231"
    5. "312"
    6. "321"

    Given n and k, return the kth permutation sequence.

    Note: Given n will be between 1 and 9 inclusive.

    这题蛮有意思,按照之前permutation的思路挨个枚举,直到枚举到当前位置,这种做法很不幸超时了,仔细想想也是,这题并不需要把之前每一步permutation的结果都获取到,来到当前结果,所以一个更好的办法是基于组合数学的。即根据k的大小,直接估计所要求的数。具体思路可以参考 Yanbing Shi的博客

    同样先通过举例来获得更好的理解。以n = 4,k = 9为例:
     
    1234
    1243
    1324
    1342
    1423
    1432
    2134
    2143
    2314  <= k = 9
    2341
    2413
    2431
    3124
    3142
    3214
    3241
    3412
    3421
    4123
    4132
    4213
    4231
    4312
    4321
     
    最高位可以取{1, 2, 3, 4},而每个数重复3! = 6次。所以第k=9个permutation的s[0]为{1, 2, 3, 4}中的第9/6+1 = 2个数字s[0] = 2。
     
    而对于以2开头的6个数字而言,k = 9是其中的第k' = 9%(3!) = 3个。而剩下的数字{1, 3, 4}的重复周期为2! = 2次。所以s[1]为{1, 3, 4}中的第k'/(2!)+1 = 2个,即s[1] = 3。
     
    对于以23开头的2个数字而言,k = 9是其中的第k'' = k'%(2!) = 1个。剩下的数字{1, 4}的重复周期为1! = 1次。所以s[2] = 1.
     
    对于以231开头的一个数字而言,k = 9是其中的第k''' = k''/(1!)+1 = 1个。s[3] = 4
    代码如下:
    class Solution(object):
        def getPermutation(self, n, k):
            """
            :type n: int
            :type k: int
            :rtype: str
            """
            nums = range(1,n+1)
            res = []
            factorial = [1] * n
            for i in xrange(1, n):
                factorial[i] = factorial[i-1]*i
            i = n-1
            k -= 1
            while  i >= 0:
                index = k / factorial[i]
                res.append(str(nums.pop(index)))
                k = k % factorial[i]
                i -= 1
    
            return ''.join(res)

    值得注意的是k一开始要减1,因为pop数的时候最终需要pop第0位。比如对1,1的例子,1/1=1,但是此时只有一位,是无法pop出结果的,所以将k先减1是比较好的做法。

    这种做法时间复杂度位O(n^2),按index pop是O(n)的时间复杂度,而空间复杂度也为O(n).

  • 相关阅读:
    xamarin ios html5 video.js 无法播放
    限制WPF textbox 字符最大值
    .net 客户端 WCF Binding 多次迭代
    10款无需编程的App DIY开发工具
    国外一些好用的UX/UI设计工具和资源分享
    成功网页设计师的七大必备技能
    提升编程能力的11个技巧
    2015程序员推荐书单
    前端工作流程自动化——Grunt/Gulp 自动化
    HTML5初学者福利!11个在线学习网站推荐
  • 原文地址:https://www.cnblogs.com/sherylwang/p/5568133.html
Copyright © 2020-2023  润新知