步骤
从下标0开始,一直往后走,每一次都有 len(candidates) - i 种选择,当数组总和等于目标时说明符合,当数组总和大于目标时,说明此路不通,终止
图解
代码
func main() {
var temp []int // 中间变量
candidates := []int{1,2,4} // 需要组合的数据
var ret [][]int // 结果存放
target := 4 // 目标
backTrack(0,temp,target,candidates, &ret)
}
func backTrack(start int, temp []int, target int, candidates []int, result *[][]int) {
//当target==0说明刚好给出的列表里的存在元素相加等于target
if target < 0 {
return
} else if target == 0 {
current := make([]int, len(temp))
copy(current, temp)
*result = append(*result, current)
}
//进行主体循环
for i := start; i < len(candidates); i++ {
temp = append(temp, candidates[i])
//递归
backTrack(i, temp, target-candidates[i], candidates, result)
//回溯
temp = temp[:len(temp)-1]
}
}
输出结果: