Problem
Given a collection of numbers,nums, that might contain duplicates, return all possible unique permutations in any order.
Examples
Constraints
1 <= nums.length <= 8-10 <= nums[i] <= 10
Documentation Index
Fetch the complete documentation index at: /llms.txt
Use this file to discover all available pages before exploring further.
Tested Python solution for LeetCode 47 with 12 pytest cases. Generate a practice environment with lcpy.
lcpy gen -n 47 # by problem number
lcpy gen -s permutations_ii # by problem name
nums, that might contain duplicates, return all possible unique permutations in any order.
Input: nums = [1,1,2]
Output:
[[1,1,2],
[1,2,1],
[2,1,1]]
Input: nums = [1,2,3]
Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
1 <= nums.length <= 8-10 <= nums[i] <= 10class Solution:
# Time: O(n * n!)
# Space: O(n)
def permute_unique(self, nums: list[int]) -> list[list[int]]:
nums.sort()
result: list[list[int]] = []
used = [False] * len(nums)
def backtrack(current: list[int]) -> None:
if len(current) == len(nums):
result.append(list(current))
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
current.append(nums[i])
backtrack(current)
current.pop()
used[i] = False
backtrack([])
return result
| Time | Space |
|---|---|
| O(n * n!) | O(n) |