首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >置换Leetcode

置换Leetcode
EN

Stack Overflow用户
提问于 2019-09-16 04:57:32
回答 1查看 353关注 0票数 5

我正在解决这个leetcode排列问题,遇到了一个错误,我在返回的列表中得到了n个空列表,这些列表应该打印给定列表的不同排列。

获取output => [[], [], [], [], [], []]

预期的output=> [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]

代码语言:javascript
复制
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]))
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-09-16 05:05:38

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

票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57948125

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档