Leetcode 39. 组合总和
思路 回溯
还是以递归全排列+剪枝来搞,套用回溯模板。
var res [][]int func combinationSum(candidates []int, target int) [][]int { res = make([][]int, 0) backTracking([]int{}, candidates, target, 0) return res } func Sum(nums []int) (res int) { //求和函数,应该可以继续优化 for _, item := range nums { res += item } return } func backTracking(temp []int, nums []int, target int, start int) { if Sum(temp) == target { //如果当前的和已经满足条件,结束此分支 tmp := make([]int, len(temp)) copy(tmp, temp) res = append(res, tmp) //将当前路径的结果添加到最终结果数组中 return } if Sum(temp) > target { //如果当前数组的和已经超过target 直接停止后续节点的递归 return } length := len(nums) for i := start; i < length; i++ { temp = append(temp, nums[i]) backTracking(temp, nums, target, i) temp = temp[:len(temp)-1] } }