40. leetcode題目講解(Python): 組合總和 2 II(Combination Sum II)

題目如下:

解題思路:

這道題跟上一題(39題)非常類似,不同之處是這道題不允許重複使用candidates中的元素。我們可以直接在上一道題目的代碼上修改,遞歸的時候將 idx 加 1(需判斷是否超出candidates的範圍),另外由於題目輸入的candidates可能包含相同的元素,所以我們需要對得到的答案進行去重處理。

參考代碼:


class Solution:
    def Slover(self, candidates, target, res, path, 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:
                    idx = idx + 1
                    if idx < len(candidates):
                        self.Slover(candidates, new_target, res, path + [candidates[i]], idx)
                    else:
                        return
                    
            
    def combinationSum2(self, candidates, target):
        """
        :type candidates: List[int]
        :type target: int
        :rtype: List[List[int]]
        """
        res = []
        path = []
        idx = 0
        candidates = sorted(candidates)
        self.Slover(candidates, target, res, path, idx)
        ud_res = []
        for r in res:
            if r not in ud_res:
                ud_res.append(r)
        return ud_res


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

其它題目:[leetcode題目答案講解彙總(Python版 持續更新)]
(https://www.jianshu.com/p/60b5241ca28e)

ps:如果您有好的建議,歡迎交流 :-D,
也歡迎訪問我的個人博客 苔原帶 (www.tundrazone.com)

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