Notice
Recent Posts
Recent Comments
Link
| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | 4 | 5 | 6 | 7 |
| 8 | 9 | 10 | 11 | 12 | 13 | 14 |
| 15 | 16 | 17 | 18 | 19 | 20 | 21 |
| 22 | 23 | 24 | 25 | 26 | 27 | 28 |
Tags
- 유데미부트캠프
- 브루트포스 알고리즘
- 데이터분석
- 넘파이
- 정렬
- 취업부트캠프
- ndarray
- 데이터프레임
- 데이터시각화
- 파이썬
- pandas
- Tableau
- Leetcode
- 유데미큐레이션
- 판다스
- 시각화
- Til
- numpy
- 유데미코리아
- 부트캠프후기
- 데이터드리븐
- 태블로
- 유데미
- 백준
- DataFrame
- 그리디 알고리즘
- python
- 코딩테스트
- 스타터스부트캠프
- matplotlb
Archives
- Today
- Total
Diary, Data, IT
[LeetCode] 17. Letter Combinations of a Phone Number - Python 본문
Coding Test/LeetCode
[LeetCode] 17. Letter Combinations of a Phone Number - Python
라딘 2023. 4. 15. 01:58[LeetCode] 17. Letter Combinations of a Phone Number - Python
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까지의 숫자를 포함한 digits문자열이 주어졌을 때, 전화번호로 조합 가능한 모든 문자를 출력하세요.
숫자별로 가질 수 있는 문자들은 아래 이미지와 같습니다.

아이디어
먼저 각 숫자를 키로, 숫자에 해당하는 문자열을 값으로 하는 딕셔너리를 생성한다.
digits에 해당하는 숫자들을 차례대로 하나씩 선택하고, 점점 아래로 들어가서 가장 아래 깊이까지 도달하면 그때부터 경우의 수를 저장하는 방식으로 문제를 해결했다.
재귀함수를 통해 아래 깊이까지 점차 내려갈 수 있다.
예를 들어 digits = '23'이라면 2에 해당하는 문자열 중 첫번째인 'a'를 선택하고, 아래 깊이로 내려가서 먼저 'd'를 선택한다. 이때 깊이가 최대가 되므로 'ad'를 저장하고, 같은 깊이에서 그 다음 문자열인 'e'를 선택하는 방식이다.
코드
class Solution:
def letterCombinations(self, digits: str) -> List[str]:
#초기 설정
dic = {'2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl',
'6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz'}
result = []
def dfs(index, path): #index: 깊이
#가장 아래 깊이까지 도달, 저장할 경우의 수
if len(path) == len(digits):
result.append(path)
return
#입력값 자릿수 단위 반복
for i in range(index, len(digits)):
#숫자에 해당하는 모든 문자열 반복
for j in dic[digits[i]]:
dfs(i + 1, path + j) #i+1을 통해 아래로 들어감, path+j로 각 깊이에서 경우의 수 하나씩 할당
#예외 처리
if not digits:
return []
dfs(0, '')
return result
'Coding Test > LeetCode' 카테고리의 다른 글
| [LeetCode] 200. Number of Islands - Python (0) | 2023.04.15 |
|---|---|
| [LeetCode] 3. Longest Substring Without Repeating Characters - Python (0) | 2023.04.14 |
| [LeetCode] 937. Reorder Data in Log Files - Python (0) | 2023.04.11 |
| [LeetCode] 819. Most Common Word - Python (0) | 2023.04.11 |
| [LeetCode] 344. Reverse String - Python (0) | 2023.04.11 |