我已经编写了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]]我认为这与范围界定有关,但我不知道我做错了什么,没有返回列表。
发布于 2018-05-29 17:52:14
当您将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]]https://stackoverflow.com/questions/50590082
复制相似问题