题目描述:python
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 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. Given k will be between 1 and n! inclusive.
Example 1:app
Input: n = 3, k = 3 Output: "213"
Example 2:spa
Input: n = 4, k = 9 Output: "2314"
即:对于一个整数n,共有n!个排列,给出数字k,返回第k个全排列code
观察题目可得以下规律:blog
对于n,其中每一个字母 开头的全排列共有n-1!个,如数字3,以 1开头的共有2!个。递归
所以:m= k / (n-1)! 能够肯定出第一个数字, 将该数字加入返回值列表中。队列
k %(n-1)! 能够获得在剩余的数字列表中,该取第几个 即 k = k%(n-1)!rem
所以采用循环或者递归可解决get
这里注意边界(结束)条件: 当k%(n-1)! ==0时,实际为 以m-1开头的最后一个排列,所以,将m-1放入队列,剩下的数字倒序便可io
当k%(n-1)! == 1时,即以 m开头的第一个,将m放入队列,其他数字依次放入便可。
代码以下:
#!/usr/bin/python #coding=utf-8 class Solution(object): def getPermutation(self, n, k): """ :type n: int :type k: int :rtype: str """ res = '' step = n - 1 used = [] use = 0 remain = list(range(1, n+1)) if step == 0: return str(n) while(step != 0): maxPer = self.factorial(step) firstOrder = k / maxPer secondOrder = k % maxPer if secondOrder == 0: use = remain.pop(firstOrder-1) else: use = remain.pop(firstOrder) res = res + str(use) used.append(use) if not remain: return res if secondOrder == 1: tmp = reduce(lambda x, y: str(x)+str(y), remain) res = res + str(tmp) return res if secondOrder == 0: if not remain: return res tmpList = remain tmpList.reverse() tmp = reduce(lambda x, y: str(x)+str(y), tmpList) res = res + str(tmp) return res k = secondOrder step = step - 1 def factorial(self, n): return reduce(lambda x,y:x*y,[1]+range(2,n+1)) s = Solution() print s.getPermutation(3, 6)