60. Permutation Sequence(求全排列的第k个排列)

Posted 张乐乐章

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了60. Permutation Sequence(求全排列的第k个排列)相关的知识,希望对你有一定的参考价值。

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.

 

如果用前面2道题 的递归 非递归 都会超时。

只能用数学的方法计算。

 1 class Solution(object):
 2 
 3     def getPermutation(self, n, k):
 4         """
 5         :type nums: List[int]
 6         :rtype: List[List[int]]
 7         """
 8         k = k -1
 9         nums = list(range(1, n + 1))
10         res = ‘‘
11         while len(nums)!=0:
12             ai =int(k/self.fn(n-1))
13             res += str(nums[ai])
14             del nums[ai]
15             k = k % self.fn(n-1)
16             n = n - 1
17         return res
18     def fn(self, n):
19         res = 1
20         while n != 0:
21             res = res * n
22             n = n - 1
23         return res
24             

 

以上是关于60. Permutation Sequence(求全排列的第k个排列)的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode(60):Permutation Sequence

LeetCode31 Next Permutation and LeetCode60 Permutation Sequence

60. Permutation Sequence

60. Permutation Sequence

Permutation Sequence LT60

60. Permutation Sequence