使用 Stack Pop 在 Python 中回溯

Backtracking in Python with Stack Pop

我正在使用回溯来获取非重复 nums 列表的排列。例如 nums = [1, 2, 3],输出应该是 '[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[ 3,1,2],[3,2,1]]。我被递归堆栈中的弹出元素困住了。任何人都可以帮助我我的代码有什么问题。谢谢

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))

我得到了 [[1], [1], [2], [2], [3], [3]]。

你的代码在逻辑上是正确的。您只需要使用 copy.

为什么会这样 - 请在 SO 上查看此 answer

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]]