78.子集--77.组合

78,子集

递归

python 复制代码
class Solution(object):
    def subsets(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        # 结果
        ans=[]
        # 临时结果
        dp_=[]
        def dfs(nums,index):
            if index==len(nums):
                # 保存结果
                co_dp=dp_[:]
                ans.append(co_dp)
                return 
            # 终止条件
            # 不选:
            dfs(nums,index+1)
            # 选
            dp_.append(nums[index])
            dfs(nums,index+1)
            dp_.pop()

        dfs(nums,0)
        return ans

77.组合

递归 没有优化

python 复制代码
class Solution(object):
    def combine(self, n, k):
        """
        :type n: int
        :type k: int
        :rtype: List[List[int]]
        """
                # 结果
        ans=[]
        # 临时结果
        dp_=[]
        def dfs(index,k):
            if index==n+1:                
                # 保存结果
                # 加一个判断len(dp_==k)
                if len(dp_)==k:
                    co_dp=dp_[:]
                    ans.append(co_dp)
                return 
            # 终止条件
            # 不选:
            dfs(index+1,k)
            # 选
            dp_.append(index)
            dfs(index+1,k)
            dp_.pop()

        dfs(1,k)
        return ans

优化后

python 复制代码
class Solution(object):
    def combine(self, n, k):
        """
        :type n: int
        :type k: int
        :rtype: List[List[int]]
        """
                # 结果
        ans=[]
        # 临时结果
        dp_=[]
        def dfs(index,k):
            # 提前判断终止
            if len(dp_)>k or len(dp_)+n-index+1<k:
                return
            if index==n+1:                
                # 保存结果
                # 加一个判断len(dp_==k)
                # if len(dp_)==k:
                co_dp=dp_[:]
                ans.append(co_dp)
                return 
            # 终止条件
            # 不选:
            dfs(index+1,k)
            # 选
            dp_.append(index)
            dfs(index+1,k)
            dp_.pop()

        dfs(1,k)
        return ans
相关推荐
程序员Xu28 分钟前
【OD机试题解法笔记】连续出牌数量
笔记·算法·深度优先
CoovallyAIHub41 分钟前
单目深度估计重大突破:无需标签,精度超越 SOTA!西湖大学团队提出多教师蒸馏新方案
深度学习·算法·计算机视觉
CoovallyAIHub44 分钟前
从FCOS3D到PGD:看深度估计如何快速搭建你的3D检测项目
深度学习·算法·计算机视觉
偷偷的卷1 小时前
【算法笔记 day three】滑动窗口(其他类型)
数据结构·笔记·python·学习·算法·leetcode
北京地铁1号线1 小时前
Zero-Shot(零样本学习),One-Shot(单样本学习),Few-Shot(少样本学习)概述
人工智能·算法·大模型
凤年徐2 小时前
【数据结构】时间复杂度和空间复杂度
c语言·数据结构·c++·笔记·算法
kualcal2 小时前
代码随想录17|二叉树的层序遍历|翻转二叉树|对称二叉树
数据结构·算法
满分观察网友z2 小时前
从混乱到有序:我用“逐层扫描”法优雅搞定公司组织架构图(515. 在每个树行中找最大值)
后端·算法
满分观察网友z2 小时前
一行代码的惊人魔力:从小白到大神,我用递归思想解决了TB级数据难题(3304. 找出第 K 个字符 I)
后端·算法
字节卷动3 小时前
【牛客刷题】活动安排
java·算法·牛客