首页 > 解决方案 > 代码不返回排列

问题描述

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

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

标签: pythonmathscopepermutation

解决方案


当您附加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您可以附加to的浅表副本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]]

推荐阅读