美文网首页
60. Permutation Sequence

60. Permutation Sequence

作者: April63 | 来源:发表于2018-06-21 13:37 被阅读0次

    超时了。。。
    回溯法

    class Solution(object):
        def getPermutation(self, n, k):
            """
            :type n: int
            :type k: int
            :rtype: str
            """
            res = []
            temp = ''
            visit = [0 for i in range(n)]
            self.huisu(visit, [0], n, k, res, temp)
            return res[0]
        def huisu(self, visit, count, n, k, res, temp):
            if count[0] >= k:
                return
            if len(temp) == n:
                count[0] += 1
                if count[0] == k:
                    res.append(temp)
                return
            for i in range(1, n+1):
                if visit[i-1] == 0:
                    visit[i-1] = 1
                    self.huisu(visit, count, n, k, res, temp + str(i))
                    visit[i-1] = 0
    

    一种没超时的办法久久没法提交??

    class Solution(object):
        def getPermutation(self, n, k):
            """
            :type n: int
            :type k: int
            :rtype: str
            """
            ans=''
            nums=[]
            s=1
            for i in range(n):
                nums.append(i+1)
                s*=(i+1)
            k-=1
            while nums:
                s=s/n
                j,k=divmod(k,s)             
                ans+=str(nums.pop(j))
                n-=1            
            return ans
        
    

    相关文章

      网友评论

          本文标题:60. Permutation Sequence

          本文链接:https://www.haomeiwen.com/subject/fyyqyftx.html