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

【Leetcode题解】 同时被 2 个专栏收录
146 篇文章 0 订阅
145 篇文章 10 订阅

## 题目大意

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
点赞
• 0
评论
• 0
收藏
• 一键三连
• 扫一扫，分享海报

04-27 3148

01-26 538
02-02 53
05-20 1338
01-20 383
09-14 54
11-25 1829
06-16 5108
03-21 1608
03-15 4132
10-22 1622
©️2021 CSDN 皮肤主题: Age of Ai 设计师:meimeiellie

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