LeetCode 39 組合總和 回溯演算法

2021-10-09 16:02:49 字數 888 閱讀 7688

給定乙個無重複元素的陣列 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.退出條件

①sum == target時,得到乙個結果。

②sum > target時,由於數字是從小到大加入組合的,所以這次組合失敗。

2.遞迴

dfs(i, sum, target, candidates)

位置右移到i,sum += candidates[i]

3.回溯

退出dfs後 將加入的i位置的元素移除 前往i+1位置進行遞迴

class

solution

else

if(sum > target)

for(

int i = pos; i < candidates.length; i++

)return;}

public list

>

combinationsum

(int

candidates,

int target)

}

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...