码迷,mamicode.com
首页 > 其他好文 > 详细

90. Subsets II

时间:2017-07-11 21:03:38      阅读:141      评论:0      收藏:0      [点我收藏+]

标签:.so   contain   index   tps   leetcode   tco   post   get   .com   

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

 

 

Sol 1:

 

Iteration.

Sort first.

 

class Solution(object):
    def subsetsWithDup(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        
        # iterately 
        res = [[]]
        nums.sort()
        for num in nums:
            res += [item + [num] for item in res if item + [num] not in res]
        return res

 

 

Sol 2:

 

DFS.

 

class Solution(object):
    def subsetsWithDup(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        
        # DFS
        
        res = []
        nums.sort()
        self.dfs(nums, 0, [], res)
        return res
    
    def dfs(self, nums, index, path, res):
        res.append(path)
        for i in range(index, len(nums)):
            if i > index and nums[i] == nums[i-1]:
                continue
            self.dfs(nums, i+1, path+[nums[i]], res)

 

 

 

Similar question:

78. Subsets

 

90. Subsets II

标签:.so   contain   index   tps   leetcode   tco   post   get   .com   

原文地址:http://www.cnblogs.com/prmlab/p/7152041.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!