Leetcode 60. Permutation Sequence

Posted lettuan

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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):

  1. "123"
  2. "132"
  3. "213"
  4. "231"
  5. "312"
  6. "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的主要内容,如果未能解决你的问题,请参考以下文章

#Leetcode# 60. Permutation Sequence

一天一道LeetCode#60. Permutation Sequence.

Leetcode60 Permutation Sequence

Leetcode 60. Permutation Sequence

leetcode [60] Permutation Sequence

LeetCode60:Permutation Sequence