Leetcode39. 組合總和-python

難度:中等

給定一個無重複元素的數組 candidates 和一個目標數 target ,找出 candidates 中所有可以使數字和爲 target 的組合。

candidates 中的數字可以無限制重複被選取。

說明:

所有數字(包括 target)都是正整數。
解集不能包含重複的組合。 
示例 1:

輸入: candidates = [2,3,6,7], target = 7,
所求解集爲:
[
  [7],
  [2,2,3]
]


示例 2:

輸入: candidates = [2,3,5], target = 8,
所求解集爲:
[
  [2,2,2,2],
  [2,3,3],
  [3,5]
]

思路:用遞歸來完成:例如以示例1爲例:對2,3,6,7進行遞歸調用,當遞歸2時,再次對2,3,6,7進行調用,如果當前數組大於目標值就return 空;當等於目標值時,加入到結果數組中,否則就繼續遞歸。

遇見的問題:對3、6、7進行遞歸時,不應該加入之前的數組,舉例對6遞歸時,後續只遞歸6、7.加個判斷即可解決。

代碼如下:

class Solution(object):
    def combinationSum(self, candidates, target):
        """
        :type candidates: List[int]
        :type target: int
        :rtype: List[List[int]]
        """
        #結果集合
        result = []
        #遞歸函數
        def a(temp,res):
            #失敗
            if temp > target:
                return
            #找到符合的序列
            if temp == target:
                result.append(res[:])
                return
            for i in candidates:
                #防止重複的方法是,不讓其找在當前元素以前的元素
                if res and res[-1] > i:
                    continue
                a(temp + i, res + [i])
        #函數調用
        a(0, [])
        return result

 

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