美文网首页
39.leetcode题目讲解(Python): 组合总和(Co

39.leetcode题目讲解(Python): 组合总和(Co

作者: 夏山闻汐 | 来源:发表于2018-12-02 15:04 被阅读38次

题目如下:

题目

解题思路

这道题目的解题思路是,通过 sorted 函数先对候选数字的list进行排序,然后再使用递归的方法来获取各个解。

参考代码, beats 84%

class Solution:
    def Solver(self, res, path, candidates, target, idx):
        for i in range(idx, len(candidates)):
            new_target = target - candidates[i]
            if new_target < 0:
                return
            else:
                if new_target == 0:
                    res.append(path + [candidates[i]])
                else:
                    self.Solver(res, path + [candidates[i]], candidates,
                                new_target, i)

    def combinationSum(self, candidates, target):
        """
        :type candidates: List[int]
        :type target: int
        :rtype: List[List[int]]
        """
        path = []
        res = []
        candidates = sorted(candidates)
        self.Solver(res, path, candidates, target, 0)
        return res

源码地址:
https://github.com/jediL/LeetCodeByPython

其它题目:[leetcode题目答案讲解汇总(Python版 持续更新)]
(https://www.jianshu.com/p/60b5241ca28e)

ps:如果您有好的建议,欢迎交流 :-D,
也欢迎访问我的个人博客 苔原带 (www.tundrazone.com)

相关文章

网友评论

      本文标题:39.leetcode题目讲解(Python): 组合总和(Co

      本文链接:https://www.haomeiwen.com/subject/emqbqqtx.html