LintCode:数字组合

来源:互联网 发布:it分销商 编辑:程序博客网 时间:2024/05/29 12:17

LintCode:数字组合

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

import copyclass 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()
0 0
原创粉丝点击