Skip to content

Commit

Permalink
Create permutations-II.py
Browse files Browse the repository at this point in the history
Has to implement DFS in order to operate fast enough to pass the new conditions. 
Uses copy.deepcopy to prevent lists from being retroactively destroyed
  • Loading branch information
gabedonnan authored Jan 15, 2023
1 parent d459021 commit aa2b383
Showing 1 changed file with 24 additions and 0 deletions.
24 changes: 24 additions & 0 deletions permutations-II.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import copy
class Solution:
def permuteUnique(self, nums: List[int]) -> List[List[int]]:
res = []
nums = sorted(nums)
used = [False]*len(nums)
li = []
self.dfs(nums, used, li, res)
return res

def dfs(self, nums, used, li, res):
if len(li) == len(nums):
res.append(copy.deepcopy(li))
return
for i in range(len(nums)):
if used[i]:
continue
if i > 0 and (nums[i] == nums[i-1]) and not used[i-1]:
continue
used[i] = True
li.append(nums[i])
self.dfs(nums, used, li, res)
used[i] = False
li.pop()

0 comments on commit aa2b383

Please sign in to comment.