简体   繁体   中英

Backtracking in Python with Stack Pop

I'm using backtracking to get permutations of non-duplicates nums list. Eg 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.

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

Your code is logically right. All what you need it's to use copy .

Why it so - please check this answer on 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]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM