47. Permutations II
Medium LeetCodeGiven a collection of numbers, nums
, that might contain duplicates, return all possible unique permutations in any order.
Example 1
Input: nums = [
1,1,2
]Output: [[1,1,2],[1,2,1],[2,1,1]]
Example 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]]
Constraints
1 <= nums.length <= 8
-10 <= nums[i] <= 10
How to solve the problem
- Backtracking (DFS)
python
class Solution:
def permuteUnique(self, nums: List[int]) -> List[List[int]]:
nums.sort() # Sort the array to facilitate duplicate checking
result = []
self.backtracking(nums, [], [False] * len(nums), result)
return result
def backtracking(self, nums, path, used, result):
# If the current path includes all numbers, add a copy to result
if len(path) == len(nums):
result.append(path[:])
return
for i in range(len(nums)):
# Skip used elements, or skip duplicates unless the previous duplicate has been used in this branch
if (i > 0 and nums[i] == nums[i - 1] and not used[i - 1]) or used[i]:
continue
used[i] = True # Mark the element as used
path.append(nums[i]) # Add element to current path
self.backtracking(nums, path, used, result) # Recurse
path.pop() # Backtrack: remove the last element
used[i] = False # Mark the element as unused for future paths
Complexity
- Time complexity: O(K*C(n, k))
- Space complexity: O(K*C(n, k))
Comments
No comments yet. Be the first to comment!