回溯算法–超时
class Solution:
def getPermutation(self, n: int, k: int) -> str:
self.res = {}
cur = ""
nums = [str(i) for i in range(1, n+1)]
self.pos = 0
# print(nums)
self.backtrack(nums[:], cur)
# print(self.res)
return self.res[str(k-1)]
def backtrack(self, nums, cur):
if len(nums) == 0:
l = str(self.pos)
self.res[l] = cur
self.pos += 1
return
for i, num in enumerate(nums):
new_num = nums[:]
cur += num
new_num.remove(num)
self.backtrack(new_num[:], cur[:])
cur = cur[:-1]
return
缩小问题规模
https://leetcode-cn.com/problems/permutation-sequence/solution/di-kge-pai-lie-by-leetcode-solution/
class Solution:
def getPermutation(self, n: int, k: int) -> str:
factorial = [1] # 记录阶乘
for i in range(1, n):
factorial.append(factorial[-1] * i)
k -= 1
ans = list()
valid = [1] * (n+1)
for i in range(1, n+1):
order = k // factorial[n-i] + 1 # 找到第order小的位置,即为当前结果
for j in range(1, n+1):
order -= valid[j]
if order == 0:
ans.append(str(j))
valid[j] = 0
break # 结束内层循环
k %= factorial[n-i] # 更新k
return "".join(ans)