编程语言
首页 > 编程语言> > 子集——力扣(python)

子集——力扣(python)

作者:互联网

第一种思路:直接遍历,遇到一个数就把所有子集加上该数组成新的子集,遍历完毕即是所有子集

class Solution:
    def subsets(self, nums: List[int]) -> List[List[int]]:
        res = [[]]
        for i in range(len(nums)-1,-1,-1):
            for subset in res[:]: res.append(subset+[nums[i]])
        return res

第二种:位运算

class Solution:
    def subsets(self, nums: List[int]) -> List[List[int]]:
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        results = []
        
        subsets_size = 2 ** len(nums)

        n = 0
        while n < subsets_size:
            subset = []
            
            i = 0
            bits = n
            while bits > 0:
                if bits & 1 == 1:
                    subset.append(nums[i])
                i += 1
                bits = bits >> 1
            
            n += 1
            results.append(subset)
        
        return results

 

 

参考:https://leetcode-cn.com/problems/subsets/comments/

标签:subset,subsets,nums,python,List,力扣,int,子集,bits
来源: https://blog.csdn.net/weixin_38517705/article/details/99216594