leetcode39-組合總和(二)

leetcode39-組合總和(二)

給定一個數組 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]
]

題解

使用回溯法+DFS搜索

class Solution:
    def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
        n = len(candidates)
        if n==0: return []
        candidates.sort()
        path = []
        res = []
        self._dfs(candidates,0,n,path,res,target)
        return res
    def _dfs(self, candidates, i, n, path, res, target):
        if target==0:
            if path[:] not in res:
                res.append(path[:])
        for j in range(i,n):
            # if j>0 and candidates[j]==candidates[j-1]:
            #     continue
            if candidates[j] > target: break
            path.append(candidates[j])
            self._dfs(candidates,j+1,n,path,res,target-candidates[j])
            path.pop()
        
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章