Subsets II

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

Subsets的差别在给出的数字中有重复元素,但是返回的子集不能有重复.其实和Permutations II的思路是一样的,即上一步和下一步之间可以有重复,如[1,2] -->[1,2,2].但是同一步枚举不同位置时不可以,比如

[1] -->[1,2],选了第一个2,之后由[1]出发选择第二个2作为第二个元素就不可以.代码如下:

class Solution(object):
    def subsetsWithDup(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        if not nums:
            return []
        res = []
        nums.sort()
        res.append([])
        self.dfs(nums, 0, [], res)
        return res
        
    def dfs(self, nums, start, sub, res):
        for i in xrange(start, len(nums)):
            if i > start and nums[i] == nums[i-1]: #枚举同一步有重复则跳过
                continue
            sub.append(nums[i])
            res.append(sub+[])
            self.dfs(nums, i+1, sub, res)
            sub.pop()

 

posted on 2016-07-25 17:07  Sheryl Wang  阅读(112)  评论(0编辑  收藏  举报

导航