https://leetcode.com/problems/letter-combinations-of-a-phone-number/description/
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
문제 소개
- 요약: 특정 휴대폰 숫자를 눌렀을 때, 나올 수 있는 모든 알파벳 조합을 반환하시오
- 관련 토픽: DFS
- 후기: DFS를 이용해서 쉽게 풀 수 있었다.
Code & 설명
def letterCombinations(self, digits):
if not digits:
return []
answer = []
alpabet = [
["a", "b", "c"],
["d", "e", "f"],
["g", "h", "i"],
["j", "k", "l"],
["m", "n", "o"],
["p", "q", "r", "s"],
["t", "u", "v"],
["w", "x", "y", "z"]
]
def three_bits(word):
if len(word) == len(digits):
answer.append(word)
else:
now = int(digits[len(word)]) - 2
for i in range(len(alpabet[now])):
three_bits(word + alpabet[now][i])
three_bits("")
return answer
- DFS를 재귀적으로 사용하여 풀었다.
- alpabet 배열을 어떻게 없애고 싶어서 다른 코드를 살펴봤는데 다른 분들도 하나하나 다 적었다.
- 다른 점은 배열 대신 딕셔너리를 사용했다.
- 배열 크기가 고정되어 있어서 속도상의 차이는 나지 않은 것 같다. 하지만 다음에는 나도 딕셔너리를 사용해야겠다.
'TIL > 이전 풀이' 카테고리의 다른 글
[python] Leetcode 46. Permutations (0) | 2022.12.13 |
---|---|
[python] Leetcode 49. Group Anagrams (0) | 2022.12.13 |
[python] Leetcode 98. Validate Binary Search Tree (0) | 2022.12.13 |
[python] Leetcode 79. Word Search (0) | 2022.12.13 |
[python] Leetcode 54. Spiral Matrix (0) | 2022.12.13 |