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

Full spread II (Python)

編輯:Python

LeetCode link

Time complexity O(n * n!)
The case where a repeating element is added to the full permutation , And the results should not be repeated

Ideas :

  1. Sort the original list first , Make the repeating elements all close together
  2. Then prune on the basis of full arrangement
class Solution:
def permuteUnique(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]:
# Because I've been right nums Array is out of order here nums[i] == nums[i - 1] Indicates that it may be a duplicate Branch 
# But there are two cases With [1,1,2] give an example 
# situation 1、 The first layer selects i=0 Situated 1 The second layer chose i=1 Situated 1 This is normal Should not be excluded 
# situation 2、 The first layer selects i=1 Situated 1 This is a duplicate branch Need to skip 
# therefore , Just judge nums[i] == nums[i - 1] Still not enough 
# With the help of selected Array 
# situation 1 nums[i] Although and num[i - 1] equal however selected[i - 1] is True indicate nums[i - 1] It was selected on the upper floor here num[i] Can be selected normally 
# situation 2 select[i - 1] is False It shows that this is a repeated situation Should exclude 
if i > 0 and nums[i] == nums[i - 1] and not selected[i - 1]:
continue
# Mark selected 
selected[i] = True
# add value 
path.append(nums[i])
doit()
# Roll back 
path.pop()
selected[i] = False
# Sort first to ensure that repeated elements are close together So you can see nums[i] Whether and nums[i - 1] Equal to judge whether to repeat 
nums.sort()
doit()
return res_list

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