代码不返回排列

时间:2018-05-29 17:45:58

标签: python math scope permutation

我编写了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]]

我认为它与范围界定有关但我不知道我做错了什么让列表没有返回任何内容。

1 个答案:

答案 0 :(得分:2)

当您将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]]