在做Leetcode的第39題的時(shí)候,看到網(wǎng)上一個(gè)用遞歸的解法,很簡(jiǎn)潔。于是重寫(xiě)了一遍。

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()時(shí)會(huì)將result中的數(shù)也pop出來(lái) 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)
文章標(biāo)題:對(duì)pythonappend與淺拷貝的實(shí)例講解-創(chuàng)新互聯(lián)
URL鏈接:http://www.chinadenli.net/article20/diopjo.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供微信公眾號(hào)、動(dòng)態(tài)網(wǎng)站、品牌網(wǎng)站建設(shè)、自適應(yīng)網(wǎng)站、全網(wǎng)營(yíng)銷(xiāo)推廣、電子商務(wù)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶(hù)投稿、用戶(hù)轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話(huà):028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容