【发布时间】: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