题目描述:
给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。candidates 中的数字可以无限制重复被选取。
链接:https://leetcode-cn.com/problems/combination-sum
示例:
解题思路:回溯
a)用目标值target减去数组candidates中的元素值,得到新的目标值target,不断与数组candidates中的元素值执行减法操作,至目标值为0或负数; b)目标值为0的路径值组合则为所求; 举例:candidates = [2,3,6,7] target = 7 7 -2 -3 -6 -7 5 4 1 0 -2 -3 -6 -7 3 2 -1 -2 -2 -3 -6 -7 1 0 -3 -4
代码实现:
class Solution(object):
def combinationSum(self, candidates, target):
"""
组合总和
解题思路:回溯
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
res = []
path = []
length = len(candidates)
start = 0 # 加入start起始位置,是为结果中不含重复项;即当-2这一分枝结束后,下一分枝将不会出现-2操作;
self.dfs(candidates, target, start, length, res, path)
return res
def dfs(self, candidates, target, start, length, res, path):
if target < 0: # 目标数小于0时,直接结束不做操作
return
if target == 0: # 目标数为0时,将path加入结果集中
res.append(path)
return
for idx in range(start, length):
self.dfs(candidates, target - candidates[idx], idx, length, res, path + [candidates[idx]])