免費做海報的網(wǎng)站效果好的東莞品牌網(wǎng)站建設(shè)
第七章 回溯算法
- 77.組合
- 代碼隨想錄文章詳解
- 總結(jié)
77.組合
以n=5,k=3為例
(1)for循環(huán)遍歷,遞歸選擇符合要求的值加入path,len(path)==k時,返回
statrtIndex保證每次遞歸取到的值不重復(fù)
剪枝:i<=n-(k-len(path))+1 后續(xù)需要k-len(path)個值,因為i可選區(qū)間左閉右閉,故+1
func combine(n int, k int) [][]int {res := [][]int{}path := []int{}var helper func(n, k, startIndex int)helper = func(n, k, startIndex int) {if len(path) == k {tmp := make([]int, k)copy(tmp, path)res = append(res, tmp)return}for i:= startIndex; i <= n; i++ {path = append(path, i)helper(n, k, i+1)path = path[:len(path) - 1]}}helper(n, k, 1)return res
}
(2)遞歸枚舉每個值,選/不選
若不選當(dāng)前值,遞歸下一個值;若選當(dāng)前值,加入結(jié)果集,回溯,保證當(dāng)前狀態(tài)不影響下一次遞歸
func combine(n int, k int) [][]int {res := [][]int{}path := []int{}var helper func(n, k, i int)helper = func(n, k, i int) {if len(path) == k {tmp := make([]int, k)copy(tmp, path)res = append(res, tmp)return}if i > n {return}helper(n, k, i + 1)path = append(path, i)helper(n, k, i + 1)path = path[:len(path) - 1]}helper(n, k, 1)return res
}
代碼隨想錄文章詳解
理論基礎(chǔ)
77.組合
總結(jié)
循環(huán)嵌入遞歸,循序漸進。感謝代碼隨想錄訓(xùn)練營。