【力扣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. 每一个元素都有选和不选两个选择
相关推荐
jyyyx的算法博客14 小时前
LeetCode 面试题 16.22. 兰顿蚂蚁
算法·leetcode
TL滕14 小时前
从0开始学算法——第五天(初级排序算法)
数据结构·笔记·学习·算法·排序算法
Q741_14714 小时前
C++ 高精度计算的讲解 模拟 力扣67.二进制求和 题解 每日一题
c++·算法·leetcode·高精度·模拟
夏乌_Wx14 小时前
练题100天——DAY19:含退格的字符串+有序数组的平方
算法
Ayanami_Reii14 小时前
进阶数据结构应用-线段树扫描线
数据结构·算法·线段树·树状数组·离散化·fenwick tree·线段树扫描线
leoufung14 小时前
LeetCode 98 Validate Binary Search Tree 深度解析
算法·leetcode·职场和发展
水木姚姚14 小时前
C++ begin
开发语言·c++·算法
浅川.2514 小时前
xtuoj 素数个数
数据结构·算法
jyyyx的算法博客14 小时前
LeetCode 面试题 16.18. 模式匹配
算法·leetcode
uuuuuuu14 小时前
数组中的排序问题
算法