LeetSolved

Find solutions to all LeetCode problems here.

47.

Permutations II

Medium

Problem Description

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

Examples

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]]

Constraints

Approach to Solve

Use backtracking with sorting to generate all possible unique permutations.

Code Implementation

class Solution:
    def permuteUnique(self, nums: List[int]) -> List[List[int]]:
        def backtrack(path, counter):
            if len(path) == len(nums):
                result.append(path[:])
                return
            for num in counter:
                if counter[num] > 0:
                    path.append(num)
                    counter[num] -= 1
                    backtrack(path, counter)
                    path.pop()
                    counter[num] += 1
        
        result = []
        backtrack([], Counter(nums))
        return result

Explanation

This solution uses a backtracking approach to generate all possible permutations of the input array nums, ensuring no duplicates. Here's a detailed explanation of the algorithm:

  1. Initialize an empty list result to store the resulting permutations.
  2. Sort the input array nums to handle duplicates.
  3. Call the backtrack function with the initial parameters: result, an empty list path, the sorted input array nums, and a boolean array used to track which elements have been used in the current permutation.
  4. In the backtrack function:
    • If the size of path is equal to the length of nums, add a copy of path to result and return.
    • Iterate through each number in nums:
      • If the number is already in path, skip it.
      • Add the number to path.
      • Recursively call backtrack with the updated parameters.
      • Remove the last added number from path (backtrack).
  5. Return the result list containing all unique permutations of nums.

The time complexity is O(n!) for generating all permutations, and the space complexity is O(n) for the recursion stack and to store each permutation.

Complexity

  • Time Complexity: O(n * n!)
  • Space Complexity: O(n)
Code copied to clipboard!