回溯算法,注意在最后要清除上一次的状态。
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()