不返回置换的代码

2024-06-02 07:22:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经编写了python代码来排列数字列表

class Solution:

    def __init__(self):
        self.permutations = []

    def permute_helper(self, nums, chosen):

        if nums == []:
            print chosen
            self.permutations.append(chosen)
        else:
            for num in nums:
                #choose
                chosen.append(num)
                temp = nums[:]
                temp.remove(num)

                #explore
                self.permute_helper(temp, chosen)

                #un-choose
                chosen.remove(num)

    def permute(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        self.permute_helper(nums, [])
        return self.permutations

s = Solution()
input = [1,2,3]
print s.permute(input)

它返回:

[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
[2, 3, 1]
[3, 1, 2]
[3, 2, 1]
[[], [], [], [], [], []]

我希望所有的排列都像这样出现在返回的列表中

[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
[2, 3, 1]
[3, 1, 2]
[3, 2, 1]
[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]

我认为这与范围界定有关,但我不知道我做错了什么,让列表什么也不返回


Tags: selfhelper列表deftempnumlistprint
1条回答
网友
1楼 · 发布于 2024-06-02 07:22:34

当您将chosen附加到self.permutations时,您在该事实之后对chosen所做的任何更改也将影响self.permutations的每个元素。通过稍后调用chosen.remove,也可以从self.permutations中删除数字。考虑这个简单的例子:

>>> a = [1,2,3]
>>> b = []
>>> b.append(a)
>>> b.append(a)
>>> b.append(a)
>>> a.remove(2)
>>> b
[[1, 3], [1, 3], [1, 3]]

您可以将chosen的浅拷贝附加到self.permutations,在这种情况下,之后对chosen所做的更改对self.permutations没有影响

    if nums == []:
        print chosen
        self.permutations.append(chosen[:])

结果:

[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
[2, 3, 1]
[3, 1, 2]
[3, 2, 1]
[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]

相关问题 更多 >