Permutation Sequence 全排列的第k个数 python

Permutation Sequence 全排列的第k个数 python_第1张图片

代码如下

class Solution(object):

    def getpertimute(self, n, k):
        k -= 1
        factorial = 1
        result = []
        array = list(range(1, n+1))

        for i in range(2, n):
            factorial *= i
        for i in range(n-1, 0, -1):
            print '------', array
            print i
            index = k // factorial
            result.append(str(array[index]))
            array.remove(array[index])
            k %= factorial
            factorial //= i
        result.append(str(array[0]))
        print "".join(result)
        return "".join(result)

if __name__ == "__main__":
    n = input('input number int n(0~9):')
    k = input('which one pertitute:')
    assert 10 > n > 0
    p = 1
    for i in range(2, n + 1):
        p *= i
    assert k <= p
    solution = Solution()
    solution.getpertimute(n, k)



你可能感兴趣的:(Permutation Sequence 全排列的第k个数 python)