1. 程式人生 > >60. Permutation Sequence(求全排列的第k個排列)

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

self. while enc n-1 span all list clu post

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個排列)