모눈종이에 사각사각
[Leetcode 17] Letter Combinations of a Phone Number 본문
🍎 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 digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.
⚾ 코드
def solution(digits):
# 알파벳 매핑
alpha = [[], [],
['a', 'b', 'c'],
['d', 'e', 'f'],
['g', 'h', 'i'],
['j', 'k', 'l'],
['m', 'o', 'n'],
['p', 'q', 'r', 's'],
['t', 'u', 'v'],
['w', 'x', 'y', 'z']]
grid = []
answer = []
# grid 생성
for num in digits:
grid.append(alpha[int(num)])
# dfs 함수 작성
def dfs(x, y, word):
# 다음 숫자 탐색 하기 위해 1증가
x += 1
temp = word
if x < len(grid):
for i in range(len(grid[x])):
word = temp
word += grid[x][i]
dfs(x, y, word)
else:
# 다음에 탐색 할 숫자가 없다면 append
answer.append(word)
if len(grid) == 0:
return answer
for i in range(len(grid[0])):
mix = grid[0][i]
dfs(0, i, mix)
return answer
print(solution("23"))
🔔 해결과정 & 깨달은 점
- dfs의 아이디어를 사용해 풀었다.
- 재귀 함수의 원리를 이해하기 위해 한 줄씩 코드를 실행시키며 원리를 이해했다.
- 내가 작성한 alpha를 리스트의 형태가 아닌 딕셔너리의 형태로도 입력할 수 있다.
{"2": "abc", "3":"def", "4": "ghi" ... }
word = temp
하는 부분을 보다 간소화 시킬 수 있을 것 같다. 다시 한 번 풀때는 더 간결한 코드로 풀어 볼 것이다.
'CodingTest > Leetcode' 카테고리의 다른 글
[Leetcode 200] Number of Islands (0) | 2022.02.18 |
---|
Comments