Published:
Updated:

  • Reference
  • not in을 μ‚¬μš©ν•˜λŠ” 것보닀 dfs의 정석인 visited λ‘œμ§μ„ μ‚¬μš©ν•˜λŠ” 게 더 빠름
    • λŒ€μ‹ , indexκ°€ μ–΄μ©” 수 없이 ν•„μš”ν•΄μ§


Solution

from typing import List


class Solution:
    def permute(self, nums: List[int]) -> List[List[int]]:
        answer = []

        def dfs(elements: List[int]) -> None:
            if len(elements) == len(nums):
                answer.append(elements[:])
                return

            for num in nums:
                if num not in elements:
                    elements.append(num)
                    dfs(elements)
                    elements.pop()

        for num in nums:
            dfs([num])

        return answer


Another Solution

from typing import List


class Solution:
    def permute(self, nums: List[int]) -> List[List[int]]:
        answer = []
        visited = [False] * len(nums)

        def dfs(index: int, elements: List[int]) -> None:
            if len(elements) == len(nums):
                answer.append(elements[:])
                return

            visited[index] = True

            for j, n in enumerate(nums):
                if not visited[j]:
                    elements.append(n)
                    dfs(j, elements)
                    elements.pop()

            visited[index] = False

        for i, num in enumerate(nums):
            dfs(i, [num])

        return answer


IterTools Solution

import itertools
from typing import List


class Solution:
    def permute(self, nums: List[int]) -> List[List[int]]:
        return itertools.permutations(nums)

Leave a comment