1. 程式人生 > >【LeetCode每天一題】Permutation Sequence(排列序列)

【LeetCode每天一題】Permutation Sequence(排列序列)

listing wing contain 沒有 其他 nbsp ret 開始 kth

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 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.

Given k will be between 1 and n! inclusive.

Example 1:

Input: n = 3, k = 3                Output: "213"

Example 2:

Input: n = 4, k = 9               Output: "2314"

思路

  看到這道題的時候我用的之前做的排列方法一樣,就是一個一個的進行組合,當排列了第k個時直接結束排列,然後返回結果。但是提交時卻是時間超時了。因為當n為9時,輸出最後一個序列的運行時間特別長。這時我在想有沒有什麽其他的辦法來解決這個問題,然後我當時想到了因為排列時是從第一個元素開始的,相當於每次固定一個元素,然後對後面的 n-1個元素進行排序。根據這個我們可以想到是不是可以根據n-1組合得數量來求得以第一個元素為準有多少種排列數。然後和k進行計算得到當前是對第幾個元素為準得進行排列。然後直接以這個元素進行排列得到結果。這樣可以省去前面元素排列時所耗費的時間。寫出來也成功通過了。

  但是運行結果的效率還是比較低,我們可以在上面的方法繼續改進,就是使用循環每次根據k的值都從1至n個元素中挑選出一個,直到k為0時,然後組合結果。得到最終的序列,也就是第K個序列。但是這種辦法自己沒能寫出來。
解決代碼(第一種思路)



 1 class Solution(object):
 2     def getPermutation(self,n, k):
 3         if n == 1:
 4             return 1
 5         nums = [i for i in range(1, n + 1)]
 6         res = []
7 dp = [1]* (n-1) 8 for i in range(2, len(dp)+1): # 計算 n-1個元素有多少種組合數, 這裏使用的數組來記錄前一個元素的的組合數 9 dp[i-1] = i*dp[i-2] 10 num = dp[-1] 11 index = 0 12 if k > num: # 根據k來判斷當前是對第幾個元素來進行排列。 13 index = k//num 14 if k % num == 0: 15 index -= 1 16 k -= num*index 17 path = [nums[index]] 18 nums.pop(index) 19 self.permutation(nums, path, res, [0], k) 20 return ‘‘.join(str(i) for i in res[-1]) 21 22 23 def permutation(self, nums, path, res, k, kth): # 排列組合 24 if not nums: 25 res.append(path) 26 k[0] += 1 27 return 28 for i in range(len(nums)): 29 self.permutation(nums[:i] + nums[i + 1:], path + [nums[i]], res, k, kth) 30 if k[0] >= kth: # 第K個排列時直接返回 31 return

【LeetCode每天一題】Permutation Sequence(排列序列)