【问题标题】:Why isn't append() appending the swapped list. It is appending original string but printing swapped list为什么不 append() 附加交换的列表。它正在附加原始字符串但打印交换列表
【发布时间】:2019-10-19 16:33:31
【问题描述】:

nums:列出我需要找到的排列。 Leetcode 问题:46。 我需要返回一个包含列表所有排列的矩阵。当它到达回溯结束时,我打印 nums 甚至将 nums 附加到矩阵。它正在打印交换的数字,但它正在附加原始数字。有人可以解释一下原因或如何解决这个问题吗?

我尝试将 v 创建为全局矩阵,但它不起作用。

class Solution:
    def permutation(self, v, nums, l, r):
        if l == r-1:
            print(nums)
            v.append(nums)
        else:
            for i in range(l, r):
                nums[i], nums[l] = nums[l], nums[i]
                self.permutation(v, nums, l+1, r)
                nums[i], nums[l] = nums[l], nums[i]
            return v

    def permute(self, nums: List[int]) -> List[List[int]]:
        v = []
        return self.permutation(v, nums, 0, len(nums))
'''

Input:[1,2,3]
Printing:
[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
[2, 3, 1]
[3, 2, 1]
[3, 1, 2]
Output:
[[1,2,3],[1,2,3],[1,2,3],[1,2,3],[1,2,3],[1,2,3]]

Expected:
[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]

【问题讨论】:

    标签: python-3.x string permutation


    【解决方案1】:

    您每次都将nums 列表的相同引用附加到v。您应该改为附加nums 列表的副本。

    变化:

    v.append(nums)
    

    到:

    v.append(nums[:])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-30
      • 1970-01-01
      • 1970-01-01
      • 2020-09-03
      • 2021-06-26
      • 2010-11-22
      相关资源
      最近更新 更多