原题地址:https://oj.leetcode.com/submissions/detail/5341904/
题意:
The set [1,2,3,…,n] contains a total of n! unique permutations.
By listing and labeling all of the permutations in order,
We get the following sequence (ie, for n = 3):
"123"
"132"
"213"
"231"
"312"
"321"
Given n and k, return the kth permutation sequence. Note: Given n will be between 1 and 9 inclusive.
解题思路:刚开始用dfs,但一直TLE。貌似用java和c++写dfs可以过,看来python确实慢啊。只能采用一种更巧妙的思路了。
class Solution:
# @return a string
# def dfs(self, n, k, string, stringlist):
# if len(stringlist) == n:
# Solution.count += 1
# if Solution.count == k:
# print stringlist
# return
# for i in range(len(string)):
# self.dfs(n, k, string[:i]+string[i+1:], stringlist+string)
# def getPermutation(self, n, k):
# string = ''
# for i in range(n): string += str(i+1)
# Solution.count = 0
# self.dfs(n, k, string, '')
def getPermutation(self, n, k):
res = ''
k -= 1
fac = 1
for i in range(1, n): fac *= i
num = [1, 2, 3, 4, 5, 6, 7, 8, 9]
for i in reversed(range(n)):
curr = num[k/fac]
res += str(curr)
num.remove(curr)
if i !=0:
k %= fac
fac /= i
return res