首页 > 代码库 > Leetcode 60. Permutation Sequence
Leetcode 60. Permutation Sequence
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.
思路: 看一个例子 n=4: k=15。每一个色块的大小都是(n-1)! = 6。k在第三个色块里,所以第1个数字是3。然后在紫色块中调用递归函数,这是我们剩余的数字是[124],等价的 k = 15-6*2 = 3。边界条件是 len(nums) == 1。注意这个求在第几个色块里的操作是 (k-1)//factorial(n-1),和求矩阵里的第k个元素是在哪一行哪一列类似。
1 class Solution(object): 2 def getPermutation(self, n, k): 3 """ 4 :type n: int 5 :type k: int 6 :rtype: str 7 """ 8 nums = list(range(1, n+1)) 9 res = [] 10 self.helper(nums, res, k) 11 a = map(str, res) 12 return ‘‘.join(a) 13 14 def helper(self, nums, res, k): 15 16 n = len(nums) 17 if n == 1: 18 res += nums 19 return 20 21 i = (k-1)/math.factorial(n-1) 22 res += [nums[i]] 23 nums = nums[:i]+nums[i+1:] 24 k = k - i*math.factorial(n-1) 25 self.helper(nums, res, k) 26
Leetcode 60. Permutation Sequence
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。