Search code examples
pythonstackbacktrackingcircular-permutations

Backtracking in Python with Stack Pop


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.

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


Solution

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