我已经编写了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]]
我认为这与范围界定有关,但我不知道我做错了什么,让列表什么也不返回
当您将
chosen
附加到self.permutations时,您在该事实之后对chosen
所做的任何更改也将影响self.permutations
的每个元素。通过稍后调用chosen.remove
,也可以从self.permutations
中删除数字。考虑这个简单的例子:您可以将
chosen
的浅拷贝附加到self.permutations
,在这种情况下,之后对chosen
所做的更改对self.permutations
没有影响结果:
相关问题 更多 >
编程相关推荐