39.组合总和

Given a set of candidate numbers (candidates) (without duplicates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.

The same repeated number may be chosen from candidates unlimited number of times.

Note:
All numbers (including target) will be positive integers.
The solution set must not contain duplicate combinations.

Example 1:

Input: candidates = [2,3,6,7], target = 7,
A solution set is:
[
[7],
[2,2,3]
]

Example 2:

Input: candidates = [2,3,5], target = 8,
A solution set is:
[
[2,2,2,2],
[2,3,3],
[3,5]
]

思路

使用回溯法。

  1. 首先对数组排序。
  2. 对于[2,3,6,7],target=7,首先找到2,target变成5,再找到2,target变成3,在找到2,此时path = [2,2,2],target变成1,1已经小于path的最后一个值,说明在原数组中已经找不到,则回退一步,变成[2,2],再从[3,6,7]中遍历,找到3

代码

class Solution:
    def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
        result = []
        candidates.sort()
        self._combinationSum(candidates, target, 0, [], result)
        return result

    def _combinationSum(self, candidates, target, index, path, res):
        if target == 0:
            res.append(path)
            return
        if path and target < path[-1]:
            return
        for i in range(index, len(candidates)):
            self._combinationSum(candidates, target - candidates[i], i, path + [candidates[i]], res)

也可以通过栈来遍历

 def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
        result = []
        candidates.sort()
        stack = [(0, list(), target)]
        can_len = len(candidates)
        while stack:
            i, path, remain = stack.pop()
            while i < can_len:
                if candidates[i] == remain:
                    result.append(path + [candidates[i]])
                if path and remain < path[-1]:
                    break
                stack += [(i, path + [candidates[i]], remain - candidates[i])]
                i += 1
        return result
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,448评论 0 10
  • 更多精彩内容,请关注【力扣中等题】。 题目 难度:★★★☆☆类型:数组方法:回溯法 给定一个无重复元素的数组 ca...
    玖月晴阅读 1,517评论 0 0
  • 题目链接难度:中等 类型:深度优先搜索 给定一个无重复元素的数组 candidates 和一个目...
    wzNote阅读 1,059评论 0 4
  • 题目给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所...
    HITZGD阅读 258评论 0 0
  • 本想写个长篇小说的,还是决定写个短篇小说。这是2018年6月写的一篇未完结的小说稿! 没错,你没看错,我是小三,你...
    淑女_2e7d阅读 1,447评论 17 26