Leetcode 39. 组合总和(回溯)—— python

1. 题目描述

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

说明:
所有数字(包括 target)都是正整数。
解集不能包含重复的组合。

示例 1:
输入: candidates = [2,3,6,7], target = 7,
所求解集为:
[
[7],
[2,2,3]
]
(LeetCode)链接:https://leetcode-cn.com/problems/combination-sum

2. 解题思路

这题的思路类似于深度遍历,之前刷二叉树距离现在有一段时间了,忘记了这种解题思路。

思路:

  • 当遍历的值大于 > target时,就不需要再往下遍历了(继续往下遍历会超出运行时间)。
  • 当遍历的值 < target时,就把这个值放入temp列表,并且target-当前遍历的值
  • 当target == 0时,说明之前遍历的值加起来刚好等于target,所以把temp存储的值放入结果列表。

3. 代码实现

class Solution:
    def combinationSum(self, candidates, target):
        candidates.sort()
        self.res = []
        self.DFS(candidates, target, 0, [])
        return self.res

    def DFS(self, candidates, target, start, temp):
        if target == 0:
            return self.res.append(temp)
        for i in range(start, len(candidates)):
            if candidates[i] > target:
                return
             # 设置start的目的,会保存上一次取的i,如果符合条件的话, 这一次可以重复取
            self.DFS(candidates, target - candidates[i], i, temp + [candidates[i]])
发布了77 篇原创文章 · 获赞 9 · 访问量 6748

猜你喜欢

转载自blog.csdn.net/u013075024/article/details/96140841