程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Full Permutation (Python)

編輯:Python

LeetCode link

to flash back Time complexity O(n * n!)

Time complexity analysis :

  1. First time from n Number selected Second times from n - 1 Choose a few … Total choices n!
  2. At the end of recursion Copy array time complexity O(n)
  3. comprehensive 1 2 The sum O(n * n!)

Move the selected number to the left each time Next time select... From the numbers on the right

class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
''' hold nums The array is divided into left and right sides Maintain a boundary index Every time Move the selected element from the remaining elements to the left '''
n = len(nums)
res_list = []
def doit(first):
if first == n:
res_list.append(nums[:])
# Each layer selects one of the remaining elements on the right 
for i in range(first, n):
# The selected elements are added to the left 
nums[i], nums[first] = nums[first], nums[i]
# Boundary index +1 Go to the next floor 
doit(first + 1)
# after Remember to swap the elements back Start the next cycle 
nums[i], nums[first] = nums[first], nums[i]
doit(0)
return res_list

Use an array of tags of the same size to indicate whether you have previously selected

class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
res_list = []
path = []
nums_len = len(nums)
# An array of tags of the same size To mark whether a subscript has been selected 
selected = [False for _ in range(nums_len)]
def doit():
if len(path) == nums_len:
res_list.append(path[:])
return
for i in range(nums_len):
if not selected[i]:
# Mark selected 
selected[i] = True
# add value 
path.append(nums[i])
doit()
# Roll back 
path.pop()
selected[i] = False
doit()
return res_list

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved