题目描述:
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:
Input: n = 3, k = 3 Output: "213"
Example 2:
Input: n = 4, k = 9 Output: "2314"
即:对于一个整数n,共有n!个排列,给出数字k,返回第k个全排列
观察题目可得如下规律:
对于n,其中每个字母 开头的全排列共有n-1!个,如数字3,以 1开头的共有2!个。
因此:m= k / (n-1)! 可以确定出第一个数字, 将该数字加入返回值列表中。
k %(n-1)! 可以得到在剩余的数字列表中,该取第几个 即 k = k%(n-1)!
因此采用循环或者递归可解决
这里注意边界(结束)条件: 当k%(n-1)! ==0时,实际为 以m-1开头的最后一个排列,因此,将m-1放入队列,剩下的数字倒序即可
当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)