每日一题-——LeetCode(78)子集

时间:2019-09-09
本文章向大家介绍每日一题-——LeetCode(78)子集,主要包括每日一题-——LeetCode(78)子集使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

给定一组不含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。
输入: nums = [1,2,3]
输出:
[
[3],
  [1],
  [2],
  [1,2,3],
  [1,3],
  [2,3],
  [1,2],
  []
]

class Solution:
    #回溯法
    def subsets(self, nums):        
        if not nums:
            return []
        res = []
        n = len(nums)

        def helper(idx, temp_list):
            res.append(temp_list)
            for i in range(idx, n):
                helper(i + 1, temp_list + [nums[i]])

        helper(0, [])
        return res

LeetCode(90)子集2

给定一个可能包含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。
说明:解集不能包含重复的子集。
输入: [1,2,2]
输出:
[
[2],
[1],
[1,2,2],
[2,2],
[1,2],
[]
]

class Solution:
    
    def subsetsWithDup1(self, nums):
        if not nums:
            return []
        n = len(nums)
        res = []
        nums.sort()
        # 思路2
        def helper2(idx, temp_list):
            res.append(temp_list)
            for i in range(idx, n):
                if i > idx and  nums[i] == nums[i - 1]:
                    continue
                helper2(i + 1, temp_list + [nums[i]])

        helper2(0, [])
        return res

原文地址:https://www.cnblogs.com/fighting25/p/11494788.html