码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2018-02-15 13:17:55      阅读:159      评论:0      收藏:0      [点我收藏+]

标签:gpo   排列   post   span   follow   code   des   log   contains   

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

标签:gpo   排列   post   span   follow   code   des   log   contains   

原文地址:https://www.cnblogs.com/zle1992/p/8449422.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!