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
相关推荐
天桥下的卖艺者12 小时前
R语言手搓一个计算生存分析C指数(C-index)的函数算法
c语言·算法·r语言
Espresso Macchiato12 小时前
Leetcode 3715. Sum of Perfect Square Ancestors
算法·leetcode·职场和发展·leetcode hard·树的遍历·leetcode 3715·leetcode周赛471
草莓熊Lotso13 小时前
《C++ Stack 与 Queue 完全使用指南:基础操作 + 经典场景 + 实战习题》
开发语言·c++·算法
敲上瘾13 小时前
单序列和双序列问题——动态规划
c++·算法·动态规划
太过平凡的小蚂蚁13 小时前
策略模式:让算法选择像点菜一样简单
算法·策略模式
科研小白_16 小时前
基于遗传算法优化BP神经网络(GA-BP)的数据时序预测
人工智能·算法·回归
Terry Cao 漕河泾16 小时前
基于dtw算法的动作、动态识别
算法
Miraitowa_cheems19 小时前
LeetCode算法日记 - Day 73: 最小路径和、地下城游戏
数据结构·算法·leetcode·职场和发展·深度优先·动态规划·推荐算法
野蛮人6号19 小时前
力扣热题100道之560和位K的子数组
数据结构·算法·leetcode
Swift社区20 小时前
LeetCode 400 - 第 N 位数字
算法·leetcode·职场和发展