【力扣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. 每一个元素都有选和不选两个选择
相关推荐
我想进大厂33 分钟前
图论---朴素Prim(稠密图)
数据结构·c++·算法·图论
我想进大厂38 分钟前
图论---Bellman-Ford算法
数据结构·c++·算法·图论
AIGC大时代40 分钟前
高效使用DeepSeek对“情境+ 对象 +问题“型课题进行开题!
数据库·人工智能·算法·aigc·智能写作·deepseek
CODE_RabbitV1 小时前
【深度强化学习 DRL 快速实践】近端策略优化 (PPO)
算法
Wendy_robot2 小时前
【滑动窗口+哈希表/数组记录】Leetcode 438. 找到字符串中所有字母异位词
c++·算法·leetcode
程序员-King.2 小时前
day49—双指针+贪心—验证回文串(LeetCode-680)
算法·leetcode·贪心算法·双指针
转基因3 小时前
Codeforces Round 1020 (Div. 3)(题解ABCDEF)
数据结构·c++·算法
我想进大厂4 小时前
图论---Kruskal(稀疏图)
数据结构·c++·算法·图论
@Aurora.4 小时前
数据结构手撕--【二叉树】
数据结构·算法
victd4 小时前
什么是AutoRec?
算法