我写了一个小程序来打印出数组的所有排列-假设输入为[1,2,3]
。我正在使用回溯来生成解决方案。
我的问题是我可以看到结果已更新为所需值(基于打印类属性result
的日志),但未返回。实际上返回的答案是[[],[],[],[],[],[]]
–我不明白。
class Solution:
def __init__(self):
self.result = []
def permute(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
c = self.permuteHelper(nums, [])
print("finally, result:", self.result)
return self.result
def permuteHelper(self, nums, chosen):
print("permuteHelper: nums", nums, "chosen:", chosen)
if len(nums) == 0:
print("returning:", chosen)
self.result.append(chosen)
print("result:", self.result)
return self.result
index = 0
for n in nums:
nums.pop(index)
chosen.append(n)
c = self.permuteHelper(nums, chosen)
nums.insert(index, n)
chosen.remove(n)
index+=1
这是我得到的输出:
permuteHelper: nums [1, 2, 3] chosen: []
permuteHelper: nums [2, 3] chosen: [1]
permuteHelper: nums [3] chosen: [1, 2]
permuteHelper: nums [] chosen: [1, 2, 3]
returning: [1, 2, 3]
result: [[1, 2, 3]]
permuteHelper: nums [2] chosen: [1, 3]
permuteHelper: nums [] chosen: [1, 3, 2]
returning: [1, 3, 2]
result: [[1, 3, 2], [1, 3, 2]]
permuteHelper: nums [1, 3] chosen: [2]
permuteHelper: nums [3] chosen: [2, 1]
permuteHelper: nums [] chosen: [2, 1, 3]
returning: [2, 1, 3]
result: [[2, 1, 3], [2, 1, 3], [2, 1, 3]]
permuteHelper: nums [1] chosen: [2, 3]
permuteHelper: nums [] chosen: [2, 3, 1]
returning: [2, 3, 1]
result: [[2, 3, 1], [2, 3, 1], [2, 3, 1], [2, 3, 1]]
permuteHelper: nums [1, 2] chosen: [3]
permuteHelper: nums [2] chosen: [3, 1]
permuteHelper: nums [] chosen: [3, 1, 2]
returning: [3, 1, 2]
result: [[3, 1, 2], [3, 1, 2], [3, 1, 2], [3, 1, 2], [3, 1, 2]]
permuteHelper: nums [1] chosen: [3, 2]
permuteHelper: nums [] chosen: [3, 2, 1]
returning: [3, 2, 1]
result: [[3, 2, 1], [3, 2, 1], [3, 2, 1], [3, 2, 1], [3, 2, 1], [3, 2, 1]]
finally, result: [[], [], [], [], [], []]
答案 0 :(得分:1)
最简单的修复方法(添加copy
):
def permuteHelper(self, nums, chosen):
print("permuteHelper: nums", nums, "chosen:", chosen)
if len(nums) == 0:
print("returning:", chosen)
self.result.append(copy.copy(chosen)) # note!
print("result:", self.result)
return self.result
index = 0
for n in nums:
nums.pop(index)
chosen.append(n)
c = self.permuteHelper(nums, chosen)
nums.insert(index, n)
chosen.remove(n)
print("see what happen in here:", self.result) # error happens here
index += 1
此链接可能有助于: How do I pass a variable by reference?