90. Subsets II

problem

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],
  []
]
  • 题目有一点没说明白,以[1,2,3]为例,元素可以不连续比如[1,3]
  • [1,3]和[3,1]是重复解,有一个就行了

solution

  • 使用combinations求各种元素数量的下标组合
  • element = map(lambda x: nums[x], j),下标组合转换为元素
  • 元素排序,不重复的记录
from itertools import combinations
class Solution(object):
    def subsetsWithDup(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        rlist = []
        length = len(nums)
        for i in range(length + 1):
            for j in combinations(range(length), i):
                element = map(lambda x: nums[x], j)
                element.sort()
                if element not in rlist:
                    rlist.append(element)      
        return rlist

discuss

# DFS  
def subsetsWithDup(self, nums):
    res = []
    nums.sort()
    self.dfs(nums, 0, [], res)
    return res
    
def dfs(self, nums, index, path, res):
    res.append(path)
    for i in xrange(index, len(nums)):
        if i > index and nums[i] == nums[i-1]:
            continue
        self.dfs(nums, i+1, path+[nums[i]], res)
  • 转换成一个路径问题,
    长路径是段路径增量,所有路径的集合为返回值
  • 以[1,2,3,4]为例

迭代第0层,将[]空路径加入集合

第一层,会产生[1],[2],[3],[4]路径,会优先穷尽[1]下路径 DFS

第二层([1]下面)会产生[1,2] [1,3] [1,4]三个路径,优先穷尽[1,2]下路径

以此类推,从下往上一层层的求解路径,返回最上层时[1]的路径穷尽,开始求[2]的路径

  • if i > index and nums[i] == nums[i-1]: 作用为判断重复元素(nums已经排序)
posted @ 2016-11-21 10:44  Salmd  阅读(90)  评论(0)    收藏  举报