90. 子集 II

90. 子集 II

题意

给定一个可能包含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。

说明:解集不能包含重复的子集。

示例:

输入: [1,2,2]
输出:
[
[2],
[1],
[1,2,2],
[2,2],
[1,2],
[]
]

解题思路

因为加进了重复元素,那么就有可能出现重复的子集,需要在加入到结果之前进行判断是否存在(首先要进行排序,保证每个子集都是有序的),使用的思路和1是类似的;

实现

class Solution(object):
def subsetsWithDup(self, nums):
       """
      :type nums: List[int]
      :rtype: List[List[int]]
      """
       def backtracking(index, path):
           if path not in res:
               res.append(path)
           for i in range(index, len(nums)):
               backtracking(i+1, path+[nums[i]])
               
       res = []
       nums.sort()
       backtracking(0, [])
       return res

   def subsetsWithDup(self, nums):
       """
      :type nums: List[int]
      :rtype: List[List[int]]
      """
       # set中无法放set
       res = {()}
       for num in sorted(nums):
           for item in res.copy():
               res.add(tuple(list(item)+[num]))
       return [list(item) for item in res]

原文地址:https://www.cnblogs.com/George1994/p/7399878.html