【力扣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. 每一个元素都有选和不选两个选择
相关推荐
Savior`L7 小时前
二分算法及常见用法
数据结构·c++·算法
mmz12078 小时前
前缀和问题(c++)
c++·算法·图论
努力学算法的蒟蒻8 小时前
day27(12.7)——leetcode面试经典150
算法·leetcode·面试
甄心爱学习9 小时前
CSP认证 备考(python)
数据结构·python·算法·动态规划
kyle~9 小时前
排序---常用排序算法汇总
数据结构·算法·排序算法
AndrewHZ10 小时前
【遥感图像入门】DEM数据处理核心算法与Python实操指南
图像处理·python·算法·dem·高程数据·遥感图像·差值算法
CoderYanger10 小时前
动态规划算法-子序列问题(数组中不连续的一段):28.摆动序列
java·算法·leetcode·动态规划·1024程序员节
有时间要学习10 小时前
面试150——第二周
数据结构·算法·leetcode
liu****10 小时前
3.链表讲解
c语言·开发语言·数据结构·算法·链表