给定一个无重复元素的数组 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]
]
提示:
1 <= candidates.length <= 30
1 <= candidates[i] <= 200
candidate 中的每个元素都是独一无二的。
1 <= target <= 500
链接:https://leetcode-cn.com/problems/combination-sum
观察是用DFS来解,需要记录每一条分支的信息,那么就需要在定义函数时在函数中加上path。
class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
result = []
def helper(candidates, target, path, step):
# 遍历,剪枝条件是只能在step之后去找,因为排序后的数组不规定会出现重复现象
for i in range(step, len(candidates)):
if candidates[i] < target:
# 一定一定一定要copy,避免继续传下去
temp = path.copy()
temp.append(candidates[i])
helper(candidates, target-candidates[i], temp, i)
elif candidates[i] == target:
# 叶节点,最后一步,不copy
path.append(candidates[i])
result.append(path)
else:
break
# 先排序!方便剪枝
candidates.sort()
helper(candidates, target, [], 0)
return result
改进是因为dfs中candidates是一直不会变化的,就不要传入,直接利用外部的就可以,减少空间使用
class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
result = []
def helper(target, path, step):
# 遍历,剪枝条件是只能在step之后去找,因为排序后的数组不规定会出现重复现象
for i in range(step, len(candidates)):
if candidates[i] < target:
# 一定一定一定要copy,避免继续传下去
temp = path.copy()
temp.append(candidates[i])
helper(target-candidates[i], temp, i)
elif candidates[i] == target:
# 叶节点,最后一步,不copy
path.append(candidates[i])
result.append(path)
else:
break
# 先排序!方便剪枝
candidates.sort()
helper(target, [], 0)
return result
提升了蛮多,说明以后也不用传!!
记得copy的使用!!!