您的位置:首页 > 其它

LintCode:数字组合

2016-09-03 16:47 155 查看
LintCode:数字组合

回溯算法,注意在最后要清除上一次的状态。

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()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: