Leetcode 46. Permutations

2021. 1. 29. 11:57Problem Solving/LeetCode

Leetcode 46. Permutations

Permutations - LeetCode

 

Permutations - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

Logic

  1. DFS로 깊이탐색
  2. prev는 추가되고 next는 줄어들면서 dfs를 돈다

Solution

from typing import List

class Solution:
    def permute(self, nums: List[int]) -> List[List[int]]:
        prev = []
        answer = []
        def dfs(elements: List[int]):
            if len(elements) == 0:
                answer.append(prev[:])

            for e in elements:
                next = elements[:]
                prev.append(e)
                next.remove(e)
                dfs(next)
                prev.pop()

        dfs(nums)
        return answer

 

반응형