Published:
Updated:

  • Reference
  • print(element + c)λ₯Ό 찍어 봐야 이해할 수 μžˆλŠ” 둜직
    • DFS μ–΄λ ΅λ‹€!!


Solution

from typing import List


class Solution:
    # μ‘°ν•© λ¬Έμ œλ‹ˆ μˆœμ„œ κ³ λ € X
    def letterCombinations(self, digits: str) -> List[str]:
        answer = []
        # '1'μ΄λž‘ '0'은 λ§Œλ“€μ–΄μ€„ ν•„μš”κ°€ μ—†μŒ (μ˜ˆμ™Έ 처리 μ•ˆ ν•΄μ€˜λ„ λ˜λ„λ‘ λ¬Έμ œμ—μ„œ μ œμ‹œ)
        digits_map = {'2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz'}

        # (0 <= digits.length <= 4) -> μž¬κ·€λ‘œ ν‘ΈλŠ” 게 더 효과적일 λ“―
        def dfs(index: int, element: str) -> None:
            # λκΉŒμ§€ 탐색 -> λ°±νŠΈλž˜ν‚Ή
            if len(digits) == len(element):
                answer.append(element)
                return

            for i in range(index, len(digits)):
                # ν•œ 자리수의 숫자(ex. digits_map['2'])에 λŒ€ν•œ string(ex. 'abc')
                for c in digits_map[digits[i]]:
                    print(element + c)
                    dfs(i + 1, element + c)

        if not digits:
            return []

        dfs(0, '')

        return answer

Leave a comment