在做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 += 1if __name__ == '__main__': print Solution().combinationSum([2,3,6,7],7)
一開始沒看懂combinationSumRecu中的result.append(list(temp))為什么temp要加list,因為temp本身就是一個list。但是把list去掉后,結果就出現錯誤。
沒改前,結果是:
[[2, 2, 3], [7]]
改成result.append(temp)后:
[[], []]
為什么會這樣呢?list在這里做了什么工作呢?
首先,為了驗證temp每步都是一個list,我們是使用type()函數查看它的類型。
if target == 0: print type(temp),temp,result result.append(temp)
輸出為:
<type 'list'> [2, 2, 3] []<type 'list'> [7] [[7]]
可以看出,temp都是list。但是第二個result的結果不正確
可以將正確的值輸出對比一下
if target == 0: print type(temp),temp,result result.append(list(temp))
輸出為:
<type 'list'> [2, 2, 3] []<type 'list'> [7] [[7]]
可以看出,本來第二個result應該為[[2,2,3]],結果變成了[[7]].
于是猜想可能是append()淺拷貝問題。
append(temp)后又在后面進行temp.pop()操作。result實際上append的是temp的引用。當temp所指向的地址的值發生改變時,result也會跟著改變。
舉個例子驗證一下:
a = [1,2] b = [3,4] a.append(b) print a b.pop() print a
輸出結果為:
[1, 2, [3, 4]][1, 2, [3]]
要解決這個問題,需要對temp進行深拷貝后append到result中。而list(temp)就會返回temp的一個深拷貝。
除了用list(temp)以外,還可以用temp[:]進行深拷貝。
以上這篇對python append 與淺拷貝的實例講解就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持武林站長站。
新聞熱點
疑難解答