[Leetcode] 17. Letter Combinations of a Phone Number

2022. 12. 2. 15:54·코딩테스트/Python
728x90
반응형

🔗 Problem Link

 

Letter Combinations of a Phone Number - 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


❔Thinking

  • 2에서 9까지 숫자가 주어질 때, 각 숫자에 적힌 알파벳으로 가능한 조합을 모두 담은 리스트를 반환한다.

💻Solution

1. 조합을 활용한 풀이

from itertools import product
def letterCombinations(self, digits: str) -> List[str]:
    if len(digits) == 0: # digit이 없을 때 예외처리
        return []

    phone_table = {
        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']
    }

    # n에 digit에 적힌 알파벳 리스트로 담기
    n = []
    for dig in digits:
        n.append(phone_table[int(dig)])


    return [''.join(combi) for combi in list(product(*n))]

 

2. DFS를 활용한 풀이

def letterCombinations(self, digits: str) -> List[str]:
    if not digits:
        return []

    phone_table = {
        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']
    }

    result = []
    stack = [(0, [])]

    while stack:
        index, chars = stack.pop()
        if index == len(digits):
            result.append("".join(chars))
        else:
            for char in phone_table[int(digits[index])]:
                stack.append([index+1, chars + [char]])
    return result

🗝️keypoint

  1. DFS 풀이를 위해서는, stack에 현재 문자열의 길이와 다음 숫자로 가능한 문자열을 모두 포함시켜야 한다. 

'코딩테스트 > Python' 카테고리의 다른 글

[Leetcode] 77. Combinations  (0) 2022.12.02
[Leetcode] 46. Permutations  (0) 2022.12.02
[Leetcode] 200. Number of Islands  (0) 2022.12.01
[Programmers] Level 2. 행렬 테두리 회전하기  (0) 2022.12.01
[Programmers] Level 3. 가장 먼 노드  (1) 2022.12.01
'코딩테스트/Python' 카테고리의 다른 글
  • [Leetcode] 77. Combinations
  • [Leetcode] 46. Permutations
  • [Leetcode] 200. Number of Islands
  • [Programmers] Level 2. 행렬 테두리 회전하기
swwho
swwho
일상을 데이터화하다
  • swwho
    하루한장
    swwho
  • 전체
    오늘
    어제
    • 분류 전체보기 (188)
      • ML_DL (39)
        • MUJAKJUNG (무작정 시리즈) (18)
        • 딥러닝 공부하기 (21)
      • 데이터사이언스 (1)
        • EDA (1)
        • 데이터과학을 위한 통계 (0)
      • 데이터엔지니어링 (2)
      • 논문리뷰 (2)
        • Computer Vision (2)
      • Python 활용하기 (12)
      • 코딩테스트 (127)
        • Python (109)
        • MySQL (14)
      • Git (3)
      • MySQL 활용하기 (0)
      • 일상 이야기 (1)
  • 블로그 메뉴

    • 홈
    • 태그
  • 최근 글

  • 250x250
  • hELLO· Designed By정상우.v4.10.3
swwho
[Leetcode] 17. Letter Combinations of a Phone Number
상단으로

티스토리툴바