栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

leetcode 39. 组合总和 python

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

leetcode 39. 组合总和 python

题目描述:

 

题解一:

1.res保存最终解,path记录当前组合,sum记录当前path数字之和。

2.在dfs函数中,如果当前sum与target相等,则说明找到一个结果,将path加入res(需要判断res中是否已经存在和path相同的组合)。

如果当前sum小于target则从candidates中选择candidates[i]加入path,同时更新sum,然后再次调用dfs函数。

class Solution(object):
    def combinationSum(self, candidates, target):
        res = []
        path = []
        n = len(candidates)
        sum = 0
        def dfs(candidates,target,path,res,sum):
            for i in range(n):
                if sum==target:
                    newpath = sorted(path[:])
                    if newpath not in res:
                        res.append(newpath)
                    return
                if sum 

 题解二(加剪枝):

参考:https://segmentfault.com/a/1190000023954685

在考虑下一个选择的数字时,如果之前考虑过就不用重复。

class Solution(object):
    def combinationSum(self, candidates, target):
        res = []
        path = []
        n = len(candidates)
        sum = 0
        def dfs(idx,sum):
            if sum == target:
                res.append(path[:])
                return
            for i in range(idx,n):
                if sum 

 感觉剪枝没有统一的思路,需要根据题目确定,从结果来看,剪枝可以有效减少运行时间。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/325862.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号