[Leetcode][python]Combination Sum/组合总和

题目大意

给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。

candidates 中的数字可以无限制重复被选取。

解题思路

回溯,答案代码是从小到大,我一开始的思路是从大到小,然后就递归次数过多…..

代码

从小到大,将candidates的数字逐步加入,一旦超过target就将candidates切片后再加

class Solution(object):
    def combinationSum(self, candidates, target):
        """
        :type candidates: List[int]
        :type target: int
        :rtype: List[List[int]]
        """
        if not candidates:
            return []
        candidates.sort()
        result = []
        self.combination(candidates, target, [], result)
        return result

    def combination(self, candidates, target, current, result):
        # print candidates
        if current:
            # print current
            s = sum(current)
        else: 
            s = 0
        if s > target:
            return 1
        if s == target:
            result.append(current)
            return 1
        if s < target:
            for i, v in enumerate(candidates):
                flag = self.combination(candidates[i:], target, current + [v], result)
                if flag == 1:
                    break

总结

这是我已开始写的,最后报错是:

Line 15: RuntimeError: maximum recursion depth exceeded

在数据集:

[92,71,89,74,102,91,70,119,86,116,114,106,80,81,115,99,117,93,76,77,111,110,75,104,95,112,94,73]
310

说明前面的数据集对了,我觉得写的应该没问题了,应该是递归次数过多的问题,有空看下。

class Solution(object):
    result_list = []
    def combine(self, i, temp, target, candidates):
        # print 'start:', temp
        if i >= 0:
            temp.append(candidates[i])
            print temp, 'this:', candidates[i], 'sum:', sum(temp)
            if sum(temp) == target:
                self.result_list.append(temp)
                return self.combine(candidates.index(temp[0])-1, [], target, candidates)
            elif sum(temp) > target:
                temp.pop()
                return self.combine(i-1, temp, target, candidates)
            else:
                return self.combine(i, temp, target, candidates)
        else:
            # print(temp)
            if temp == []:
                return
            cut = candidates.index(temp[-1]) - 1
            # print 'daodi', cut
            temp.pop()
            return self.combine(cut, temp, target, candidates)
    def combinationSum(self, candidates, target):
        """
        :type candidates: List[int]
        :type target: int
        :rtype: List[List[int]]
        """
        i = len(candidates) - 1
        candidates.sort()
        self.combine(i, [], target, candidates)
        return self.result_list
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值