【Leetcode 39】組合總和

題目描述

在這裏插入圖片描述在這裏插入圖片描述

解題思路

解法一:回溯法

在這裏插入圖片描述
比如:candidates = [2,3,6,7],target = 7

  1. 找到全是2的組合是否能組成7,如果7-2-2-2!=0,則跳出循環,尋找2和下一個數的組合
  2. 7-2-2-3=0,則接着找7-2-3之後列表中是否有滿足的,由於列表進行了排序,發現7-2-3-2!=0,第一個數2不行就直接跳出,後面的3,6,7就不用再驗證
  3. 找到全爲3的組合是否能組成7,此時直接從下標爲1的數開始找,避免找到重複的組合,7-3-3-3!=0,跳出循環,7-3-6!=0,跳出循環
  4. 找到全爲6的組合是否能組成7,此時從下標爲2的數開始找,7-6-6!=0,跳出循環
  5. 找到全爲7的組合是否能組成7,從下標爲3的數開始找,7-7=0
  6. 結束,存儲滿足的組合

python代碼

class Solution:
    def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
        size = len(candidates)
        if size == 0:
            return []
        candidates.sort()
        path = []
        res = []
        self.__dfs(candidates, 0, size, path, res, target)
        return res
    def __dfs(self,candidates, begin, end, path, res, target):
        if target == 0:
            res.append(path[:])
            return 
        for i in range(begin,end):
            residue = target - candidates[i]
            if residue < 0:
                return
            path.append(candidates[i])
            self.__dfs(candidates, i, end, path, res, residue)
            path.pop()
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章