回溯算法,注意在最后要清除上一次的状态。
import copy
class Solution:
# @param candidates, a list of integers
# @param target, integer
# @return a list of lists of integers
def combinationSum(self, candidates, target):
# write your code here
self.ans = []
candidates = sorted(list(set(candidates)))
res = []
self.my_combinationSum(candidates, res, target, 0)
return self.ans
def my_combinationSum(self, candidates, res, target, tmp_sum):
if tmp_sum > target:
return
if tmp_sum == target:
if sorted(res) not in self.ans:
self.ans.append(copy.copy(sorted(res)))
return
for index in range(0, len(candidates)):
res.append(candidates[index])
tmp_sum += candidates[index]
self.my_combinationSum(candidates, res, target, tmp_sum)
tmp_sum -= candidates[index]
res.pop()

本文介绍了一种使用回溯算法解决数字组合问题的方法。通过递归调用和剪枝技术,实现对候选数的有效组合,以达到目标值。代码中详细展示了如何避免重复解并确保结果的有效性。

897

被折叠的 条评论
为什么被折叠?



