1. 程式人生 > 其它 >Leetcode做題記錄-子集

Leetcode做題記錄-子集

技術標籤:python演算法題leetcodedfs演算法

題:給定一個數組,返回所有可能的子集。來源:Leetcode(力扣)
1、遍歷,遇到一個數就把所有子集加上該陣列成新的子集,遍歷完畢即是所有子集。
2、將問題的解空間轉化成樹的結構,通過深度優先遍歷(回溯)得到樹的所有葉子節點即為所求結果。
在這裡插入圖片描述

class Solution:
    def subsets(self, nums: List[int]) -> List[List[int]]:
        re = []
        path = []
        self.dfs(re, nums,path,0)
return re def dfs(self,re,nums,path,index): if index >= len(nums): re.append(path.copy()) return path.append(nums[index]) self.dfs(re, nums, path, index + 1) path.pop() self.dfs(re, nums, path, index + 1)

??