为什么输出显示的值与返回值不同

时间:2018-07-26 03:45:56

标签: python permutation

我正在尝试生成置换,但我一生都无法弄清楚为什么下面的代码会按预期输出到stdout的置换,但是当我将置换附加到预先创建的列表时,它返回的值完全不同。这是代码。

class Solution:

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

def permuteHelper(self, nums, l, r):

    if l==r:
        print(nums)
        self.permutations.append(nums)
    else:
        for i in range(l, r):
            nums[l], nums[i] = nums[i], nums[l]
            self.permuteHelper(nums, l+1, r)
            nums[l], nums[i] = nums[i], nums[l]



def permute(self, nums):
    """
    :type nums: List[int]
    :rtype: List[List[int]]
    """
    self.permuteHelper(nums, 0, len(nums))

    return self.permutations


if __name__ == "__main__":
    c  = Solution()
    print c.permute([1,2,3])

它将以下内容打印到标准输出:

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

但是它的返回值是:

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

0 个答案:

没有答案