排列Leetcode

yol*_*bsn 5 python permutation

我正在解决这个leetcode排列问题,遇到了一个错误,该错误在返回的列表中获取了n个空列表,该列表可能要打印给定列表的不同排列

获得输出=> [[], [], [], [], [], []]

预期输出=> [[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]))
Run Code Online (Sandbox Code Playgroud)

san*_*ash 6

您应该这样做,s.append(l.copy())因为否则会从同一列表中弹出所有值l,这就是为什么结果包含空列表的原因。