Leetcode 39 組合總和

2021-09-24 10:00:19 字數 1259 閱讀 9497

給定乙個無重複元素的陣列 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]

]解題:回溯演算法

回溯演算法的基本思想是:從一條路往前走,能進則進,不能進則退回來,換一條路再試。

在回溯法執行時,應當:儲存當前步驟,如果是乙個解就輸出;維護狀態,使搜尋路徑(含子路徑)盡量不重複。必要時,應該對不可能為解的部分進行剪枝(pruning)。

用回溯演算法解決問題的一般步驟:

1、 針對所給問題,定義問題的解空間,它至少包含問題的乙個(最優)解。

2 、確定易於搜尋的解空間結構,使得能用回溯法方便地搜尋整個解空間 。

3 、以深度優先的方式搜尋解空間,並且在搜尋過程中用剪枝函式避免無效搜尋。

#python

class solution:

def combinationsum(self, candidates: list[int], target: int) -> list[list[int]]:

candidates.sort()

n = len(candidates)

res =

def backtrack(i, tmp_sum, tmp):

if tmp_sum > target or i == n:

return

if tmp_sum == target:

return

for j in range(i, n):

if tmp_sum + candidates[j] > target:

break

backtrack(j,tmp_sum + candidates[j],tmp+[candidates[j]])

backtrack(0, 0, )

return res

LeetCode 39 組合總和

給定乙個無重複元素的陣列candidates和乙個目標數target,找出candidates中所有可以使數字和為target的組合。candidates中的數字可以無限制重複被選取。說明 示例 1 輸入 candidates 2,3,6,7 target 7,所求解集為 7 2,2,3 示例 2 ...

leetcode39 組合總和

參考 class solution if next num.size target num next 0 邊界條件 return 對於每個元素,有兩種處理方式,選當前元素或者不選當前元素 psol.push back num next 選當前元素 search num,next,psol,targe...

LeetCode39組合總和

給定乙個無重複元素的陣列 candidates 和乙個目標數 target 找出 candidates 中所有可以使數字和為 target 的組合。candidates 中的數字可以無限制重複被選取。說明 所有數字 包括 target 都是正整數。解集不能包含重複的組合。示例 1 輸入 candid...