Today I learned
2022/01/20
회고록
항해 99, 알고리즘 1주차
교재 : 파이썬 알고리즘 인터뷰
12장 그래프
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.
Example 1:
Input: digits = "23"
Output: ["ad","ae","af","bd","be","bf","cd","ce","cf"]
Example 2:
Input: digits = ""
Output: []
Example 3:
Input: digits = "2"
Output: ["a","b","c"]
Constraints:
0 <= digits.length <= 4
digits[i] is a digit in the range ['2', '9'].
https://leetcode.com/problems/letter-combinations-of-a-phone-number/
def solution(inputNum):
dic = {
"2":"abc",
"3":"def",
"4":"ghi",
"5":"jkl",
"6":"mno",
"7":"pqr",
"8":"stv",
"9":"wxyz"
}
result = []
def recursive_num(index, alpha):
if len(alpha) == len(inputNum):
result.append(alpha)
return
for i in range(index, len(inputNum)):
for j in dic[inputNum[i]]:
recursive_num(i+1, alpha + j)
recursive_num(0,"")
return result
if __name__ == '__main__':
inputNum = '23'
result = solution(inputNum)
print('result : ' + str(result))
재귀, DFS 훈련