2017-02-13 38 views
0

它正在打印正確的值,但在結果數組中不存儲任何內容。 這裏是我的代碼:無法將局部變量複製到結果數組

def backtrack(result, nums, tempList): 
    if len(tempList) == len(nums): 
     result.append(tempList) 
    else: 
     for i in range(0, len(nums)): 
      if not tempList.count(nums[i]): 
       tempList.append(nums[i]) 
       backtrack(result, nums, tempList) 
       tempList.pop() 

nums = [1, 2, 3] 
result = [] 
backtrack(result, nums, []) 
print result 
+1

嘗試'result.append(tempList [:])'。 – jonrsharpe

+0

謝謝@jonrsharpe – Uday

回答

0

爲什麼會得到空的內部名單的原因是要修改原來的templist與tempList.pop()

你可以做的是使tempList之前的拷貝追加到result

import copy 

變化

result.append(tempList) 

mycopy = copy.deepcopy(tempList) 
result.append(mycopy) 
相關問題