leetcode39 組合總和

2021-09-06 23:01:42 字數 971 閱讀 7820

參考:

class solution 

if(next == num.

size()

|| target - num[next]

<0)

//邊界條件

return

;//對於每個元素,有兩種處理方式,選當前元素或者不選當前元素

psol.

push_back

(num[next]);

//選當前元素

search

(num, next, psol, target - num[next]

, result)

; psol.

pop_back()

;//不選當前元素,將當前元素pop

search

(num, next +

1, psol, target, result)

;//從下乙個元素開始找

}

vectorint>

>

combinationsum

(vector<

int>

&num,

int target)

};

下面這個感覺寫的不是很明白

class solution 

else

if(target <0)

return

;else}}

vectorint>>

combinationsum

(vector<

int>

& candidates,

int target)

};

採用深度搜尋遍歷,第乙個for迴圈是該層的所有元素,對於每乙個元素,先進行迴圈內的深度搜尋,target<0算是乙個剪枝條件。

**參考

動態規劃解法(未看)

思路:

LeetCode 39 組合總和

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

LeetCode39組合總和

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

leetcode39 組合總和

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