A daily problem --- LeetCode (78) subset

Given a set of no repeating element integer array nums, which returns an array of all possible subsets (power set).
Input: nums = [1,2,3]
Output :
[
[3],
  [1],
  [2],
  [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) a subset 2

Given an array of integers nums may contain duplicate elements, which returns an array of all possible subsets (power set).
Description: Solution Set can not contain duplicate subsets.
Input: [1,2,2]
Output:
[
[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

 

Guess you like

Origin www.cnblogs.com/fighting25/p/11494788.html