39.leetcode題目講解(Python): 組合總和

題目如下:

解題思路

這道題目的解題思路是,通過 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)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章