78. 子集

  1. 题目链接

  2. 解题思路:简单的回溯,就是两种情况,要这个数,不要这个数

  3. 代码

    class Solution:
        # 现在来到index位置,决定nums[index]要,还是不要,ans是最终的结果,path是一条分支的结果
        def process(self, nums: List[int], index: int, ans: List[List[int]], path: List[int]):
            if index == len(nums):
                ans.append(copy.copy(path))
                return
            # 要 
            path.append(nums[index])
            self.process(nums, index + 1, ans, path)
            path.pop()
            # 不要
            self.process(nums, index + 1, ans, path)
    
    
        def subsets(self, nums: List[int]) -> List[List[int]]:
            ans = []
            path = []
            self.process(nums, 0, ans, path)
            return ans
    
posted @ 2024-12-24 11:15  ouyangxx  阅读(6)  评论(0)    收藏  举报