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
相关推荐
凤年徐7 分钟前
【数据结构】时间复杂度和空间复杂度
c语言·数据结构·c++·笔记·算法
kualcal10 分钟前
代码随想录17|二叉树的层序遍历|翻转二叉树|对称二叉树
数据结构·算法
满分观察网友z1 小时前
从混乱到有序:我用“逐层扫描”法优雅搞定公司组织架构图(515. 在每个树行中找最大值)
后端·算法
满分观察网友z1 小时前
一行代码的惊人魔力:从小白到大神,我用递归思想解决了TB级数据难题(3304. 找出第 K 个字符 I)
后端·算法
字节卷动1 小时前
【牛客刷题】活动安排
java·算法·牛客
yi.Ist2 小时前
数据结构 —— 键值对 map
数据结构·算法
s153352 小时前
数据结构-顺序表-猜数字
数据结构·算法·leetcode
Coding小公仔2 小时前
LeetCode 8. 字符串转换整数 (atoi)
算法·leetcode·职场和发展
GEEK零零七2 小时前
Leetcode 393. UTF-8 编码验证
算法·leetcode·职场和发展·二进制运算
DoraBigHead3 小时前
小哆啦解题记——异位词界的社交网络
算法