在做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__': print Solution().combinationSum([2,3,6,7],7)
文章标题:对pythonappend与浅拷贝的实例讲解-创新互联
URL链接:https://www.cdcxhl.com/article20/diopjo.html
成都网站建设公司_创新互联,为您提供微信公众号、动态网站、品牌网站建设、自适应网站、全网营销推广、电子商务
声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联