class Solution(object): def getPermutation(self, n, k): """ :type n: int :type k: int :rtype: str """ curr = [] self.result = '' for i in range(1, n+1): curr.append(i) self.getPermutationHelper(n, k, curr) return self.result def getPermutationHelper(self, index, rest, curr): # print index, rest, '结果str:', curr if index == 0: return for i in range(index-1, -1, -1): temp = math.factorial(index-1) # print temp, i, rest - (temp * i + 1) if rest - (temp * i + 1) >= 0: self.result += str(curr[i]) curr.pop(i) # print(curr) self.getPermutationHelper(index-1, rest - (temp * i), curr) break
网上解法
其实思路是一样的,我的效率低下。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
class Solution:
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