Leetcode40. 組合總和 II-python

難度:中等

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

candidates 中的每個數字在每個組合中只能使用一次。

說明:

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

輸入: candidates = [10,1,2,7,6,1,5], target = 8,
所求解集爲:
[
  [1, 7],
  [1, 2, 5],
  [2, 6],
  [1, 1, 6]
]


示例 2:

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

思路:和39題思路差不多,採取遞歸的方法解決,只不過每次的數組需要將本次遞歸的數據給剔除掉。

代碼如下:

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

 

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