[LeetCode]78. 子集

sas???發表於2018-11-12

78. 子集
給定一組不含重複元素的整數陣列 nums,返回該陣列所有可能的子集(冪集)。
說明:解集不能包含重複的子集。
示例:
輸入: nums = [1,2,3]
輸出:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]

解法1

class Solution:
    def subsets(self, nums):
        res = []
        nums.sort()
        for i in range(0, len(nums)+1):
            self.findSub(i, res, nums, [])
        return res
    
    def findSub(self, k, res_list, nums, sub_list):
            if k == len(sub_list):
                res_list.append(sub_list)
            else:
                for i in nums:
                    self.findSub(k, res_list, nums[nums.index(i)+1:], sub_list+[i])

解法2

解法1的簡化版

class Solution:
    def subsets(self, nums):
        ans = []
        def find(cur,num):
            for i in range(len(num)):
                ans.append(cur+[num[i]])
                find(cur+[num[i]], num[i+1::])
        find([], nums)
        return ans+[[]]

解法3

class Solution:
    def subsets(self, nums):
        res = [[]]
        for num in nums :
            for temp in res[:] :
                x = temp[:]
                x.append(num)
                res.append(x)
        return res

解法4

class Solution:
    def subsets(self, nums):
        n=len(nums)
        if n==0:
            return []
        res=[]
        for i in range(2**n):
            s=i
            newlist=[]
            for j in range(n):
                bitj=s%2
                s=s//2
                if bitj:
                    newlist.append(nums[j])
            res.append(newlist)
        return res

相關文章