Python 1 - 5 lines solution. (ugly though)


  • 0

    Same idea as other solutions, just wrapped the iteration in one line with reduce .

    Any improvement suggestion?

    def getPermutation(self, n, k):
        f = math.factorial
        return reduce(lambda (ret, rst, r), x: (ret + rst.pop(r//f(x)), rst, r%f(x)),
                                               xrange(n-1, -1, -1),
                                               ("", list("123456789"), k - 1))[0]
    

    It is identical to this:

    def getPermutation(self, n, k):
        f = math.factorial
        ret, rst, k = "", list("123456789"), k - 1
        for i in xrange(n - 1, -1, -1):
            ret, k = ret + rst.pop(k // f(i)), k % f(i)
        return ret

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.