moonlightshadow123
6/24/2017 - 11:32 AM

90. Subsets II

  1. Subsets II
class Solution(object):
    def subsetsWithDup(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        # First we sort the nums first.
        self.nums = sorted(nums)
        self.res = []
        self.cur = []
        self.backtracking(0)
        return self.res
    def backtracking(self, start):
        self.res.append([each for each in self.cur])
        if len(self.nums)-1 < start:
            return
        # We use preNum to prevent duplicates.
        preNum = float('inf')
        for i in range(start, len(self.nums)):
            if self.nums[i] == preNum:
                continue
            self.cur.append(self.nums[i])
            self.backtracking(i+1)
            del self.cur[-1]

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

Given a collection of integers that might contain duplicates, nums, return all possible subsets.

Note: The solution set must not contain duplicate subsets.

For example, If nums = [1,2,2], a solution is:

[
  [2],
  [1],
  [1,2,2],
  [2,2],
  [1,2],
  []
]