解法1 典型的backtracking的解法,但是TLE了
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
|
class (object): def getPermutation(self, n, k): """ :type n: int :type k: int :rtype: str """ self.k = k self.res = "" self.dfs(n, []) return "".join([str(i) for i in self.res]) def dfs(self, n, cur): if self.k >= 0: if len(cur) == n: self.k -= 1 if self.k == 0: self.res = cur[:] return for i in range(1, n+1): if i in cur: continue cur.append(i) self.dfs(n, cur) cur.pop()
|
解法2数学思路,也不是很难
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
|
class (object): def getPermutation(self, n, k): """ :type n: int :type k: int :rtype: str """ res = "" x = range(1, n+1) while n > 0: num = k / math.factorial(n-1) if k % math.factorial(n-1) == 0: num -= 1 res += str(x[num]) x.remove(x[num]) k -= num * math.factorial(n-1) n -= 1 return res
|
近期评论