개발/Leetcode

Leetcode 17. Letter Combinations of a Phone Number

지산동고라니 2023. 6. 26. 11:39

https://leetcode.com/problems/letter-combinations-of-a-phone-number/description/

 

Letter Combinations of a Phone Number - LeetCode

Can you solve this real interview question? Letter Combinations of a Phone Number - Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. Return the answer in any order. A mapping of d

leetcode.com

문제

숫자 2~9로 이루어진 숫자 문자열이 주어진다. 이 숫자 문자열을 이용해 각 숫자가 나타내는 문자를 이용해 가능한 문자조합을 반환하라. 반환되는 조합된 문자의 순서는 신경 쓸 필요 없다.

 

각 숫자에 해당하는 문자는 핸드폰 키패드와 같다 이 때 1은 어떤 문자에도 해당하지 않는다.

 

코드

class Solution:
    def letterCombinations(self, digits: str) -> list[str]:
        if not digits:
            return []
       
        letter = {1 : [], 2: ['a','b','c'], 3: ['d','e','f'], 4: ['g','h','i'], 5:['j','k','l'], 6:['m','n','o'], 7:['p','q','r','s'], 8:['t','u','v'], 9:['w','x','y','z']}
        letters = list(map(lambda x: letter[int(x)], digits))
       
        def dfs(param):
            if len(param) == 1:
                return param[0]
           
            result = []
            d = dfs(param[1:])
            for p in param[0]:
                for p2 in d:
                    result += [p + p2]
           
            return result
               
        return dfs(letters)  

DFS의 문제 중 기본중의 기본이라고 생각하는 문제이다. 하지만 생각보다 시간이 걸렸음에 DFS에 조금 더 신경을 쓸 필요가 있음을 느낀 시간이었다.