[ Web Proxy ]
URL:
Viewing: https://raw.githubusercontent.com/Monika-R/LeetCode-Solutions/master/Python/permutation-sequence.py [Back]  [Original]

# Time:  O(n^2)
# Space: O(n)

import math

# Cantor ordering solution
class Solution(object):
    def getPermutation(self, n, k):
        """
        :type n: int
        :type k: int
        :rtype: str
        """
        seq, k, fact = "", k - 1, math.factorial(n - 1)
        perm = [i for i in xrange(1, n + 1)]
        for i in reversed(xrange(n)):
            curr = perm[k / fact]
            seq += str(curr)
            perm.remove(curr)
            if i > 0:
                k %= fact
                fact /= i
        return seq



Web Proxy Viewer  |  New URL  |  Original Page