I'm using backtracking to get permutations of non-duplicates nums list. E.g nums = [1, 2, 3], the output should be '[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]. I'm stuck on pop elements out from recursively stack. Anyone can help me what's the problem of my code. Thanks.
我正在使用回溯来获取非重复的nums列表的排列。例如nums = [1,2,3],输出应为'[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[ 3,1,2],[3,2,1]。我从递归堆栈中坚持使用pop元素。任何人都可以帮助我解决我的代码问题。谢谢。
class Solution(object):
def permute(self, nums):
visited = [False] * len(nums)
results = []
for i in range(len(nums)):
temp = []
if not visited[i]:
temp.append(nums[i])
self._helper(nums, i, visited, results, temp)
return results
def _helper(self, nums, i, visited, results, temp):
visited[i] = True
if all(visited):
results.append(temp)
for j in range(len(nums)):
if not visited[j]:
temp.append(nums[j])
self._helper(nums, j, visited, results, temp)
temp.pop()
visited[i] = False
nums = [1, 2, 3]
a = Solution()
print(a.permute(nums))
And I got [[1], [1], [2], [2], [3], [3]].
我得到[[1],[1],[2],[2],[3],[3]]。
1 个解决方案
#1
0
Your code is logically right. All what you need it's to use copy
.
您的代码在逻辑上是正确的。所有你需要的是使用副本。
Why it so - please check this answer on SO.
为什么会这样 - 请在SO上查看这个答案。
import copy
class Solution(object):
def permute(self, nums):
visited = [False] * len(nums)
results = []
for i in range(len(nums)):
temp = []
if not visited[i]:
temp.append(nums[i])
self._helper(nums, i, visited, results, temp)
return results
def _helper(self, nums, i, visited, results, temp):
visited[i] = True
if all(visited):
results.append(copy.copy(temp))
for j in range(len(nums)):
if not visited[j]:
temp.append(nums[j])
self._helper(nums, j, visited, results, temp)
temp.pop()
visited[i] = False
nums = [1, 2, 3]
a = Solution()
print(a.permute(nums))
# [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
#1
0
Your code is logically right. All what you need it's to use copy
.
您的代码在逻辑上是正确的。所有你需要的是使用副本。
Why it so - please check this answer on SO.
为什么会这样 - 请在SO上查看这个答案。
import copy
class Solution(object):
def permute(self, nums):
visited = [False] * len(nums)
results = []
for i in range(len(nums)):
temp = []
if not visited[i]:
temp.append(nums[i])
self._helper(nums, i, visited, results, temp)
return results
def _helper(self, nums, i, visited, results, temp):
visited[i] = True
if all(visited):
results.append(copy.copy(temp))
for j in range(len(nums)):
if not visited[j]:
temp.append(nums[j])
self._helper(nums, j, visited, results, temp)
temp.pop()
visited[i] = False
nums = [1, 2, 3]
a = Solution()
print(a.permute(nums))
# [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]