面试腾讯算法:组合总和
生活随笔
收集整理的這篇文章主要介紹了
面试腾讯算法:组合总和
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
? ? ??給定一個無重復元素的數組 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]
]
?
方法:搜索回溯
//一個dfs里面調用2個dfs函數,這樣的遞歸形成了一個類似樹的結構 func combinationSum(candidates []int, target int) (ans [][]int) {comb := []int{}var dfs func(target, idx int)dfs = func(target, idx int) {//idx表示遍歷到的下標if idx == len(candidates) {return}if target == 0 {//已找到組合,go二維數組appendans = append(ans, append([]int(nil), comb...))return}// 直接跳過dfs(target, idx+1)// 選擇當前數if target-candidates[idx] >= 0 {comb = append(comb, candidates[idx])dfs(target-candidates[idx], idx)comb = comb[:len(comb)-1]}}dfs(target, 0)return }??一個dfs里面調用2個dfs函數,這樣的遞歸形成了一個類似樹的結構,這個遞歸注意終止條件,每個數可以選也可以不選,因為數組里面的元素可以重復使用。力扣上的圖很詳細的表現了過程。
?
說明:圖片和代碼均來自于力扣
參考地址:https://leetcode-cn.com/problems/combination-sum/solution/zu-he-zong-he-by-leetcode-solution/
總結
以上是生活随笔為你收集整理的面试腾讯算法:组合总和的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 面试腾讯我遇到了这题:数组全排列
- 下一篇: 面试高频题:在数组中查找元素第一个和最后