-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpermutationII.py
More file actions
35 lines (26 loc) · 920 Bytes
/
permutationII.py
File metadata and controls
35 lines (26 loc) · 920 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class Solution:
def permteUnique(self, nums):
res = []
nums.sort() # Step 1: sort to group duplicates
used = [False] * len(nums)
def backtrack(path):
if len(path) == len(nums):
res.append(path[:])
return
for i in range(len(nums)):
# Step 2: skip used numbers
if used[i]:
continue
# Step 3: skip duplicates (if same as previous and previous not used)
if i > 0 and nums[i] == nums[i - 1] and not used[i - 1]:
continue
# Choose
used[i] = True
path.append(nums[i])
# Explore
backtrack(path)
# Un-Choose (backtrack)
path.pop()
used[i] = False
backtrack([])
return res