leetcode - 47. Permutations II

Description

Given 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

Solution

Similar to 46. Permutations, just need to avoid duplicates.

First sort the nums, then for each number in nums, if it’s the same as the previous one, skip.

Time complexity: o ( n ! ∗ n ) o(n! * n) o(n!n)
Space complexity: o ( n ) o(n) o(n)

Code

class Solution:
    def __init__(self,):
        self.permutation_memo = {}

    def helper(self, nums: tuple) -> list:
        if nums in self.permutation_memo:
            return self.permutation_memo[nums]
        if len(nums) == 1:
            self.permutation_memo[nums] = [nums]
            return self.permutation_memo[nums]
        res = []
        for index, item in enumerate(nums):
            if index >= 1 and nums[index - 1] == item:
                continue
            search_key = nums[:index] + nums[index + 1:]
            self.permutation_memo[search_key] = self.permutation_memo.get(search_key, self.helper(search_key))
            res += [[item] + list(np) for np in self.permutation_memo[search_key]]
        self.permutation_memo[nums] = res
        return res

    def permuteUnique(self, nums: List[int]) -> List[List[int]]:
        return self.helper(tuple(sorted(nums)))

你可能感兴趣的:(OJ题目记录,leetcode,算法,职场和发展)