【力扣100】78.子集

添加链接描述

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. 我怎么感觉这种题背下来就好?

解法二

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. 每一个元素都有选和不选两个选择
    【力扣100】78.子集_第1张图片

你可能感兴趣的:(leetcode,算法)