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             

 

posted @ 2018-02-15 13:08  乐乐章  阅读(284)  评论(0编辑  收藏  举报