Given a collection of numbers nums that might contain duplicates, return all possible unique permutations in any order.
Output: [[1,1,2],[1,2,1],[2,1,1]]
Explanation: Even though 1 appears twice, the three unique permutations are returned.
Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
Sort the array first so duplicate values are adjacent. When iterating candidates for a position, skip a candidate if it equals the previous candidate and the previous candidate was not used in the current path (meaning we are at the same level of the tree and would create a duplicate branch).
- Sort
numsto bring duplicates together. - Use a
used[]boolean array. - Skip if
i > 0 && nums[i] == nums[i-1] && !used[i-1]— this prunes sibling duplicates. - Otherwise mark, recurse, unmark, remove.
Complexity Analysis:
Time complexity: O(n * n!) worst case (all distinct). Fewer with duplicates due to pruning.
Space complexity: O(n) recursion depth.