Problem description:

Given a collection of numbers, nums, that might contain duplicates, return all possible unique permutations in any order.

Example 1:

1
2
3
4
5
Input: nums = [1,1,2]
Output:
[[1,1,2],
[1,2,1],
[2,1,1]]

Example 2:

1
2
Input: nums = [1,2,3]
Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]

Solution:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution:
def _permute(self, nums, s, k):
if len(s) == k:
print("---")
self.permutations.append(s[:])

for i in range(len(nums)):
if i > 0 and nums[i] == nums[i-1]:
continue

s.append(nums[i])
print(s)
self._permute(nums[:i] + nums[i+1:], s, k) # remove nums[i] from nums
s.pop()

def permuteUnique(self, nums: List[int]) -> List[List[int]]:
self.permutations = []
self._permute(sorted(nums), [], len(nums))
return self.permutations

output of the code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
[1]
[1, 1]
[1, 1, 1]
[1, 1, 1, 2]
---
[1, 1, 2]
[1, 1, 2, 1]
---
[1, 2]
[1, 2, 1]
[1, 2, 1, 1]
---
[2]
[2, 1]
[2, 1, 1]
[2, 1, 1, 1]
---

time complexity: $O()$
space complexity: $O()$
reference:
related problem: