1. 程式人生 > >LeetCode90 Subset II 2018.11.8

LeetCode90 Subset II 2018.11.8

題幹:

Given a collection of integers that might contain duplicates, nums, return all possible subsets (the power set).

Note: The solution set must not contain duplicate subsets.

Example:

Input: [1,2,2]
Output:
[
  [2],
  [1],
  [1,2,2],
  [2,2],
  [1,2],
  []
]

注意事項:這題與之前subset相似,注意要先將nums排序

class Solution:
    def subsetsWithDup(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        res, temp, length, nums = [[]], [], len(nums), sorted(nums)
        res = self.helper(0, length, nums, temp, res)
        return res

    def helper(self, level, length, nums, temp, result):
        for i in range(level, length, 1):
            temp.append(nums[i])
            if temp in result:
                pass
            else:
                result.append(temp[:])
            self.helper(i + 1, length, nums, temp, result)
            temp.pop()
        return result