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
相关推荐
wabs6662 小时前
关于图论【卡码网117.软件构建的思考】
数据结构·算法·软件构建·图论·卡码网
mifengxing3 小时前
LeetCode 41.缺失的第一个正数|Hard题O(n)+O(1)最优解法深度解析
java·算法·leetcode·排序算法
Tongzhi20263 小时前
从部署到运维:通芝科技无感考勤一体机的全流程效率解析
运维·数据结构·科技·算法·贪心算法
Wang's Blog4 小时前
AI Agent白手起家30: 动态示例选择器之根据长度选择 Few Shot 示例
算法
oyguyteggytrrwwwrt5 小时前
自制交叉线路识别算法
算法
手写码匠5 小时前
华为云Flexus+DeepSeek征文|Dify 多智能体协同编排实战:R1 规划 + V3 执行,构建企业 Agent 团队
人工智能·深度学习·算法·aigc
晓天衡宇•评测社区6 小时前
FSR-Bench 前沿科学推理榜单发布:GPT-5.5 居首,“会推理”未必“能答对”
算法
程序喵大人7 小时前
【C++进阶】STL算法与函数对象 - 02 sort为什么需要随机访问迭代器
开发语言·c++·算法
hanlin037 小时前
动态规划专练:力扣第121、122题
笔记·算法·leetcode
To_OC8 小时前
LC 74 搜索二维矩阵:换皮的二分查找,我居然一开始没看出来
javascript·算法·leetcode