【问题标题】:Backtracking in Python with Stack Pop使用 Stack Pop 在 Python 中回溯
【发布时间】:2018-07-09 13:34:50
【问题描述】:

我正在使用回溯来获取非重复 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]]。

【问题讨论】:

  • 欢迎来到 StackOverflow。请阅读并遵循帮助文档中的发布指南。 Minimal, complete, verifiable example 适用于此。在您发布 MCVE 代码并准确描述问题之前,我们无法有效地帮助您。我们应该能够将您发布的代码粘贴到文本文件中并重现您描述的问题。 “我被流行元素困住了[原文如此]”不是问题规范。此外,您发布的代码根本无法运行,因为您没有包含所有依赖项。

标签: python stack backtracking circular-permutations


【解决方案1】:

您的代码在逻辑上是正确的。您所需要的就是使用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]]

【讨论】:

  • 太棒了。非常感谢。
猜你喜欢
  • 2017-01-20
  • 2020-04-23
  • 1970-01-01
  • 2012-09-30
  • 2010-12-03
  • 1970-01-01
  • 2018-09-01
  • 2019-04-14
  • 1970-01-01
相关资源
最近更新 更多