39.组合总和

39.组合总和

1.题目

在这里插入图片描述

2.我的解决方案

  • 自己写的回溯算法,虽然进行了剪枝,但是从运行时间上来看,效果还是不行
class Solution:
    def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
        # 使用回溯法+剪枝函数
        def dfs(candidates, target, begin, path, res):
            if path:
                if sum(path) == target:
                    res.append(path[:])
                if sum(path) > target:  # 剪枝函数
                    return 
            for i in range(candidates.index(begin), len(candidates)):   # 为了去重,看当前的根结点,只能选取根结点本身和后面比他大的数组
                path.append(candidates[i])
                dfs(candidates, target, candidates[i], path, res)
                path.pop()

        res = [] # 结果集合(要去重)
        path = [] # 路径列表
        candidates.sort() # 为了方便进行剪枝,从小到大排列
        dfs(candidates, target, candidates[0], path, res)
        return res
  • 时间复杂度: O ( n ! ) O(n!) O(n!)
  • 空间复杂度: O ( t a r g e t ) O(target) O(target) 最差情况下递归target层

3.官方的解决方案

  • 从运行时间上看,与原方案相比节省了多于一半的时间
class Solution:
    def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
        # 别人写的回溯,采用反向思维,太精妙了
        # remian表示现在路径和和target之间的距离
        def dfs(begin, path, remain):
            for i in range(begin, len(candidates)):
                num = candidates[i]
                if num == remain:
                    path.append(num)
                    res.append(path[:])
                    path.pop()  # 还是得还原状态
                    return
                if num < remain:
                    path.append(num)
                    dfs(i, path, remain-num)    # index用i, 表示从自己的索引开始
                    path.pop()  # 回溯状态还原
                if num > remain:
                    return

        res = []
        path = []
        candidates.sort()   # 排序,减小搜索空间
        dfs(0, path, target)
        return res
  • 时间复杂度: O ( n ! ) O(n!) O(n!)
  • 空间复杂度: O ( t a r g e t ) O(target) O(target) 最差情况下递归target层
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值