leetcode

39. 组合总和

2020-02-23  本文已影响0人  十月里的男艺术家

题目

39. 组合总和

给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。

candidates 中的数字可以无限制重复被选取。

说明:

示例 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)
}
上一篇 下一篇

猜你喜欢

热点阅读