thiagowfx's avatar

Β¬ just serendipity πŸ€ (not just serendipity)

ByteByteGo: Find All Permutations

β€’ 63 words β€’ 1 min β€’ updated

ByteByteGo: Find All Permutations:

python
from typing import List

def find_all_permutations(nums: List[int]) -> List[List[int]]:
    ans = []

    def backtrack(candidate = [], visited = set()):
        if len(candidate) == len(nums):
            ans.append(candidate[:])
            return

        for num in nums:
            if num not in visited:
                candidate.append(num)
                visited.add(num)

                backtrack(candidate, visited)

                candidate.pop()
                visited.remove(num)


    backtrack()

    return ans

If we do not make a copy of candidate (candidate[:]), ans will be a mess.