我正在解决这个leetcode排列问题,遇到了一个错误,我在返回的列表中得到了n个空列表,这些列表应该打印给定列表的不同排列。
获取output => [[], [], [], [], [], []]
预期的output=> [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
def permute(nums):
l=[]
s=list()
ans=[]
return helper(nums,s,l)
def helper(nums,s,l):
if not nums:
print(l)
s.append(l)
else:
for i in range(len(nums)):
c=nums[i]
l.append(c)
nums.pop(i)
helper(nums,s,l)
nums.insert(i,c)
l.pop()
return s
print(permute([1,2,3]))发布于 2019-09-16 05:05:38
您应该执行s.append(l.copy()),因为否则您将弹出同一列表l中的所有值,这就是结果包含空列表的原因。
https://stackoverflow.com/questions/57948125
复制相似问题