Leetcode 60

Question

Solution

n个数,排列后,前(n-1)!个数以1开头,后(n-1)!个数以2开头。对于以1开头的部分,其中第一个(n-2)!部分以2开头…以此类推,可以确定所要的。

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution:
def getPermutation(self, n: int, k: int) -> str:
nums = list(range(1, n+1))
k -= 1 #考虑index=0的影响
result = ""

while n > 0:
n -= 1
index, k = divmod(k, math.factorial(n)) #商和余数
result += str(nums[index])
nums.remove(nums[index])

return result