zoukankan      html  css  js  c++  java
  • 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]

  • 相关阅读:
    smarty中ifelse、foreach以及获取数组中键值名的一个实例
    smarty逻辑运算符
    python strip()函数 介绍
    (转)论python工厂函数与内建函数
    数据结构哈希表(转)
    哈希表算法的编写
    哈希表(转)
    平衡二叉树的旋转操作
    并查集详解(转)
    Java数组技巧攻略
  • 原文地址:https://www.cnblogs.com/George1994/p/7399878.html
Copyright © 2011-2022 走看看