在做Leetcode的第39題的時(shí)候,看到網(wǎng)上一個(gè)用遞歸的解法,很簡(jiǎn)潔。于是重寫(xiě)了一遍。
網(wǎng)站建設(shè)哪家好,找成都創(chuàng)新互聯(lián)!專(zhuān)注于網(wǎng)頁(yè)設(shè)計(jì)、網(wǎng)站建設(shè)、微信開(kāi)發(fā)、微信小程序、集團(tuán)企業(yè)網(wǎng)站建設(shè)等服務(wù)項(xiàng)目。為回饋新老客戶創(chuàng)新互聯(lián)還提供了保山免費(fèi)建站歡迎大家使用!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)