반응형
Notice
Recent Posts
Recent Comments
- Today
- Total
작심삼일
[LeetCode] 17 | Letter Combinations of a Phone Number | Python 본문
728x90
반응형
문제 링크: https://leetcode.com/problems/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.
조건
- 0 <= digits.length <= 4
- digits[i] is a digit in the range ['2', '9'].
내 풀이
각 숫자에 해당되는 문자를 정리해놓는다(self.d2l).
digits의 길이는 최대 4이므로 recursion으로 푼다.
코드
class Solution:
def letterCombinations(self, digits: str) -> List[str]:
if digits == '':
return []
self.d2l = {'2': 'abc',
'3': 'def',
'4': 'ghi',
'5': 'jkl',
'6': 'mno',
'7': 'pqrs',
'8': 'tuv',
'9': 'wxyz'}
self.digits = digits
self.ans = []
self.comb(0, '')
return self.ans
def comb(self, idx, lcomb):
if idx == len(self.digits):
self.ans.append(lcomb)
return
for letter in self.d2l[self.digits[idx]]:
self.comb(idx+1, lcomb+letter)
728x90
반응형
'스터디 > 코테' 카테고리의 다른 글
[LeetCode] 1641 | Count Sorted Vowel Strings | Python (0) | 2022.05.11 |
---|---|
[LeetCode] 216 | Combination Sum III | Python (0) | 2022.05.10 |
[LeetCode] 1209 | Remove All Adjacent Duplicates in String II | Python (0) | 2022.05.06 |
[LeetCode] 1679 | Max Number of K-Sum Pairs | Python (0) | 2022.05.04 |
[LeetCode] 581 | Shortest Unsorted Continuous Subarray | Python (0) | 2022.05.03 |
Comments