它打印正确的值,但不在结果数组中存储任何内容。这是我的代码:
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
你得到空的内部列表的原因是你正在修改原始的临时列表tempList.pop()
您可以做的是在将tempList
附加到result
之前复制它:
import copy
改变
result.append(tempList)
自
mycopy = copy.deepcopy(tempList)
result.append(mycopy)