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
相关推荐
songx_9919 分钟前
leetcode10(跳跃游戏 II)
数据结构·算法·leetcode
先做个垃圾出来………1 小时前
差分数组(Difference Array)
java·数据结构·算法
hansang_IR2 小时前
【题解】洛谷 P4286 [SHOI2008] 安全的航线 [递归分治]
c++·数学·算法·dfs·题解·向量·点积
乐迪信息2 小时前
乐迪信息:AI摄像机在智慧煤矿人员安全与行为识别中的技术应用
大数据·人工智能·算法·安全·视觉检测
多恩Stone2 小时前
【3DV 进阶-2】Hunyuan3D2.1 训练代码详细理解下-数据读取流程
人工智能·python·算法·3d·aigc
惯导马工3 小时前
【论文导读】IDOL: Inertial Deep Orientation-Estimation and Localization
深度学习·算法
老姜洛克3 小时前
自然语言处理(NLP)之n-gram从原理到实战
算法·nlp
CoovallyAIHub4 小时前
基于YOLO集成模型的无人机多光谱风电部件缺陷检测
深度学习·算法·计算机视觉
CoovallyAIHub4 小时前
几十个像素的小目标,为何难倒无人机?LCW-YOLO让无人机小目标检测不再卡顿
深度学习·算法·计算机视觉
怀旧,4 小时前
【C++】19. 封装红⿊树实现set和map
linux·c++·算法