在此示例中,为什么会产生正确的结果:
nxt = path + [nums[i]]
但不是:
nxt = path ; nxt += [nums[i]]
nxt = path ; nxt.append(nums[i])
def permute(nums):
def dfs(nums, path):
if not nums: # empty, done with path
all_perms.append(path)
return
for i in range(len(nums)):
nxt = path + [nums[i]]
# nxt = path ; nxt += [nums[i]]
# nxt = path ; nxt.append(nums[i])
print(nxt)
dfs(nums[:i] + nums[i+1:], nxt)
all_perms = []
dfs(nums, [])
return all_perms
最佳答案
在此示例中,为什么会产生正确的结果:
nxt = path + [nums[i]]
这使
path
保持不变。但不是:
nxt = path ; nxt += [nums[i]]
nxt = path ; nxt.append(nums[i])
这将
nums[i]
附加到path
显然是不正确的。关于python - 生成排列时Python添加到列表的错误方法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/60243524/