Scribbling

LeetCode: 60. Permutation Sequence 본문

Computer Science/Coding Test

LeetCode: 60. Permutation Sequence

focalpoint 2021. 9. 24. 15:30
class Solution:
    def getPermutation(self, n: int, k: int) -> str:
        def factorial(n):
            if n == 1:
                return 1
            return n * factorial(n-1)
        nums = [str(i) for i in range(1, n+1)]
        if k == 1:
            return ''.join(nums)
        k -= 1
        ret = ''
        while k > 0:
            x = factorial(n-1)
            if k >= x:
                quotient = k // x
                k -= quotient * x
                ret += nums.pop(quotient)
            else:
                ret += nums.pop(0)
            n -= 1
        ret += ''.join(nums)
        return ret

'Computer Science > Coding Test' 카테고리의 다른 글

LeetCode: 62. Unique Paths  (0) 2021.09.24
LeetCode: 61. Rotate List  (0) 2021.09.24
LeetCode: 59. Spiral Matrix II  (0) 2021.09.24
LeetCode: 53. Maximum Subarray  (0) 2021.09.24
LeetCode: 57. Insert Interval  (0) 2021.09.24