給出n和k
求由1-n的數字組成的第k大的數
本來想嘗試一個個列舉的,然而超時了。因爲是n的階乘的複雜度。
首位爲1的排列總共有(n-1)!個
已知前兩位的排列共有(n-2)!個
那麼第k個排列
k//(n-1)!就是第一個數取當前剩餘數字的第幾個
k%(n-1)!//(n-2)!就是第二個數取當前剩餘數字的第幾個
class Solution(object):
def getPermutation(self, n, k):
"""
:type n: int
:type k: int
:rtype: str
"""
res = ''
nums = [i for i in range(1,n+1)]
for i in range(n-1,0,-1):
base = math.factorial(i)
current = 0
while k > base:
k -= base
current += 1
res += str(nums[current])
nums.pop(current)
res += str(nums[0])
return res