SDE & MLE Prep

47. Permutations II

Problem

nums may contain duplicates. Return every distinct permutation, in any order.

Example: [1,1,2] → [[1,1,2],[1,2,1],[2,1,1]]

Constraints: n ≤ 8.

Sort; skip nums[i] if it equals nums[i-1] and nums[i-1] is not used — i.e. only the first copy of a value may start a branch at each depth.

Complexity: O(n · n!).

class Solution:
    def permuteUnique(self, nums: List[int]) -> List[List[int]]:
        nums.sort()
        res, path, used = [], [], [False] * len(nums)

        def bt():
            if len(path) == len(nums):
                res.append(path[:])
                return
            for i in range(len(nums)):
                if used[i] or (i and nums[i] == nums[i - 1] and not used[i - 1]):
                    continue
                used[i] = True
                path.append(nums[i])
                bt()
                path.pop()
                used[i] = False

        bt()
        return res