【力扣100】78.子集

添加链接描述

python 复制代码
class Solution:
    def subsets(self, nums: List[int]) -> List[List[int]]:
        # 思路是回溯,这道题和【全排列】不一样的地方是出递归(收获)的判断条件不一样
        def dfs(path,index,res):
            res.append(path[:])
            for i in range(index,len(nums)):
                path.append(nums[i])
                dfs(path,i+1,res)
                path.pop()
        
        res=[]
        dfs([],0,res)
        return res

思路是:

  1. 回溯和递归
  2. 我怎么感觉这种题背下来就好?

解法二

python 复制代码
class Solution:
    def subsets(self, nums: List[int]) -> List[List[int]]:
        # 思路是每一个元素都有取和不取两种选择:
        def backtrack(path,index,res):
            if index==len(nums):
                res.append(path[:])
                return
            backtrack(path+[nums[index]],index+1,res)
            backtrack(path,index+1,res)
        res=[]
        backtrack([],0,res)
        return res

思路是:

  1. 每一个元素都有选和不选两个选择
相关推荐
mmz120713 小时前
双指针问题5(c++)
c++·算法
星空露珠13 小时前
lua获取随机颜色rgb转换hex
数据结构·数据库·算法·游戏·lua
mit6.82413 小时前
预hash|vector<int> dfs
算法
Zsy_05100313 小时前
【数据结构】堆简单介绍、C语言实现堆和堆排序
c语言·数据结构·算法
Rock_yzh13 小时前
LeetCode算法刷题——56. 合并区间
数据结构·c++·学习·算法·leetcode·职场和发展·动态规划
sheeta199813 小时前
LeetCode 每日一题笔记 日期:2025.12.02 题目:3623. 统计梯形的数目 I
笔记·算法·leetcode
宇来风满楼13 小时前
U-KAN复现
人工智能·深度学习·神经网络·算法·机器学习
W_chuanqi13 小时前
单目标实数参数优化:算法jSO
算法
老鱼说AI13 小时前
算法初级教学第三步:链表
数据结构·算法·链表