Skip to content

[90] Subsets II

https://leetcode.com/problems/subsets-ii/description/

  • algorithms
  • Medium (40.42%)
  • Source Code: 90.subsets-ii.py
  • Total Accepted: 196.7K
  • Total Submissions: 468.5K
  • Testcase Example: '[1,2,2]'

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

python
class Solution(object):
    def subsetsWithDup(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """

        result = set()
        if not nums: return list(result)

        self.helper(nums, 0, [], result)
        return [list(item) for item in result]

    def helper(self, nums, i, current, result):
        if i == len(nums):
            result.add(tuple(current))
            return
        else:
            self.helper(nums, i+1, current, result)
            current.append(nums[i])
            self.helper(nums, i+1, current, result)
            current.pop(-1)
#
#
# s = Solution()
# print s.subsetsWithDup([1, 2, 2])
#

Last updated: