Problem Description
Given a collection of numbers, nums, that might contain duplicates, return all possible unique permutations in any order.
Key Insights
- Sort the input array to identify and easily skip duplicates.
- Use backtracking to generate all candidate permutations.
- Maintain a visited or used array to track elements already added to the current permutation.
- When encountering a duplicate element, only use it if the previous identical element was used in the current recursion branch.
- Backtrack by removing elements and resetting their used status when moving to another branch.
Space and Time Complexity
Time Complexity: O(n * n!) in the worst-case scenario, where n is the length of the input array. Space Complexity: O(n) for the recursion stack and used data structure, plus O(n * n!) to store the permutations.
Solution
The solution employs a backtracking algorithm. First, sort the nums array to ensure that duplicates are adjacent. Then, use a recursive function to build permutations by iterating through the array and choosing elements that have not been used yet. To handle duplicates, if the current element is the same as the previous one and the previous one was not used in the current recursive path, skip the current element. This ensures that duplicate permutations are never constructed. Data structures used include:
- A list (or array) to hold the current permutation path.
- A boolean visited (or used) array to keep track of whether a number is already in the current permutation.
After constructing a permutation of the same length as nums, add it to the results list, then backtrack to explore alternative possibilities.