在做Leetcode的第39题的时候,看到网上一个用递归的解法,很简洁。于是重写了一遍。
class Solution(object):
def combinationSum(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
result,temp = [],[]
self.combinationSumRecu(sorted(candidates),result,0,temp,target)
return result
def combinationSumRecu(self, candidates, result, start, temp, target):
if target == 0:
result.append(temp) # 注意此处不能直接append(temp),否则是浅拷贝,之后temp.pop()时会将result中的数也pop出来
while start < len(candidates) and candidates[start]<=target:
temp.append(candidates[start])
self.combinationSumRecu(candidates, result, start, temp,target-candidates[start])
temp.pop()
start += 1
if __name__ == '__main__':
prin