蠡口60. Permutation Sequence

I think this is the number of essay questions, because most people can think of is like Permutations that question, as with DFS traversal get all the permutations,
and then return to the k-th permutations, time complexity T (n) = O (1 ) + n T (n-1), where the average time complexity copy depth degrees O (1),
recursively each time a excluded, so that each recursive time complexity of T (n-1).
T (n-) = O (. 1) + n-
T (n--. 1)
=> T (n-) = O ([Sigma (n-! / K!)) (K =. 1 to n-)
=> T (n-) <O (n! * Σ (1 / k!)) (k = 0 to infinity)
=> T (n-) = O (n-!). But this is the time out of!
Thus prompted IX algorithm, in full accordance with Kang opening Wiki expansion algorithm, first k- = 1, then recycled division, and I do, constantly updated k,
and removed from the inside has not been used in a corresponding number of the figures added to the final results are in. It should be noted that the number of cycles is n,
because the length of the last permutation string returned is n, and each cycle will give the corresponding figures. Submit runtime Chaoguo 95.59%, memory over 100%.

class Solution(object):
    def getPermutation(self, n, k):
        """
        :type n: int
        :type k: int
        :rtype: str
        """
        nums=range(1,n+1)
        Fac=[1]
        for i in range(1,n): Fac.append(Fac[-1]*i)
        ans,k="",k-1
        for i in range(n):
            m=k/Fac[n-1-i]
            k=k%Fac[n-i-1]
            ans+=str(nums[m])
            nums.pop(m)
        return (years)

 

Guess you like

Origin www.cnblogs.com/Leisgo/p/11696186.html
Recommended