60. Permutation Sequence

"""
60. Permutation Sequence
Medium

621

170

Favorite

Share
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 for n = 3:

"123"
"132"
"213"
"231"
"312"
"321"
Given n and k, return the kth permutation sequence.

Note:

Given n will be between 1 and 9 inclusive.
Given k will be between 1 and n! inclusive.
Example 1:

Input: n = 3, k = 3
Output: "213"
Example 2:

Input: n = 4, k = 9
Output: "2314"
"""

n个互不相同的自然数,分别是1,2,3...n,组合成数字的集合,有n!中可能,按照从小到大的顺序依次排列并编号为1,2,3,...n!,

给定一个n和序列号k(1<=k<=n!)请求第k个数字的字符串

想到的方法:

1,有办法求得数字组合的下一个,这样求k次,算法复杂度大约是knlgn(我也不确定,算出来大约是k(lg1+lg2+...+lgn)),也就是(n^2)lgn

2,可以观察根据第一个数字均匀分为了n种,总可能是n!种,因此可以将k-1和(n-1)!的商来确定首字母,根据余来确定剩下数字的排列可能性中的位置,这样算法复杂度就是o(n!)

下面是我的代码

class Solution:
    def getPermutation(self, n, k):
        """
        :type n: int
        :type k: int
        :rtype: str
        """
        if not n:
            return ""
        result = ""
        nums = [i for i in range(1, n+1)]
        numsfactorial = [1]
        for i in range(1, n):
            numsfactorial.append(numsfactorial[-1]*i)
        for i in range(n, 0, -1):
            j = (k-1)//numsfactorial[i-1]
            k = (k-1)%numsfactorial[i-1] + 1
            result += str(nums[j])
            del nums[j]
        return result

 

posted @ 2018-12-24 20:16  茫茫碧落  阅读(97)  评论(0编辑  收藏  举报