美文网首页leetcode
39. 组合总和

39. 组合总和

作者: 十月里的男艺术家 | 来源:发表于2020-02-23 20:24 被阅读0次

题目

39. 组合总和

给定一个无重复元素的数组 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)

代码

class Solution:
    def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
        self.ans = []
        candidates = sorted(candidates)

        def dfs(remain, t, path):
            if t == 0:
                self.ans.append(path)

            for i, num in enumerate(remain):
                if num > t:
                    break
                dfs(remain[i:], t-num, path+[num])

        dfs(candidates, target, [])
        return self.ans
import "sort"

func combinationSum(candidates []int, target int) [][]int {
    sort.Ints(candidates)
    res := [][]int{}
    sol := []int{}
    backtrack(candidates, sol, target, &res)
    return res
}

func backtrack(cand []int, sol []int, target int, res *[][]int) {
    if target == 0 {
        *res = append(*res, sol)
    }
    if len(cand) == 0 || cand[0] > target {
        return
    }
    sol = sol[:len(sol):len(sol)]
    backtrack(cand, append(sol, cand[0]), target-cand[0], res)
    backtrack(cand[1:], sol, target, res)
}

相关文章

  • 39. 组合总和

    39. 组合总和 很慢的dfs

  • 39. 组合总和

    39. 组合总和 https://leetcode-cn.com/problems/combination-sum...

  • 39. 组合总和

    给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可...

  • 39.组合总和

    题目给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所...

  • 39.组合总和

  • 39.组合总和

    Given a set of candidate numbers (candidates) (without du...

  • 39.组合总和

    给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可...

  • 39. 组合总和

    解题思路 典型的回溯法:递归跳出的条件return 满足题目条件将list加入容器else 未满足条件:for(遍...

  • 39. 组合总和

    题目描述 给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates...

  • 39. 组合总和

    题目 39. 组合总和 给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 can...

网友评论

    本文标题:39. 组合总和

    本文链接:https://www.haomeiwen.com/subject/xuisqhtx.html