关于golang:Leetcode专题数组39组合总和

力扣链接:
https://leetcode-cn.com/probl…
解题思路:

  1. 数组求排列的解题思路,个别都是回溯法+剪枝
  2. 回溯法是有固定套路的,依照固定套路解题即可
  3. 回溯法固定套路
    (1)定义起始地位,个别是数组的首地位;定义path门路,即选取的元素是哪些,定义总数和(该题目中须要总数和来确定循环完结)
    (2)确定循环完结条件,本题目中总和大于等于target的时候,循环完结
    (3)回溯外围代码,因为数组数字能够反复,然而[2,2,3]和[2,3,2]其实是同一个组合,那么就要保障抉择的时候,不反复path,能够通过for循环来管制,i每次往后选即可
func combinationSum(candidates []int, target int) [][]int {
    res := [][]int{}  // 定义后果
    var dfs func(start, sum int, path []int)
    dfs = func(start, sum int, path []int) {
        if sum >= target { // 循环完结剪枝
            if sum == target {
                newPath := make([]int, len(path))
                copy(newPath, path)
                res = append(res, newPath)
            }
            return
        }
        for i := start; i < len(candidates); i++ { // i每次加一,不反复选
            path = append(path, candidates[i])
            dfs(i, sum + candidates[i], path)
            path = path[:len(path) - 1]
        }
    }
    dfs(0, 0, []int{})
    return res
}

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理