Daily LeetCode 17. Letter Combinations of a Phone Number

https://leetcode.com/problems/letter-combinations-of-a-phone-number/

Medium

问题描述

Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent.

A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.

img

Example:

1
2
Input: "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].

Note:

Although the above answer is in lexicographical order, your answer could be in any order you want.

思路及代码

九宫格键盘每个数字都对应着一些字母,给一个数字串,求出所有数字对应的字母之间的组合。

首先我们建立一个字典保存每个数字对应的字母,初始化res数组为'',遍历字符串digits

在遍历过程中,保存当前数字对应的字母串,初始化数组保存当前的字母组合结果,用一个二重循环来生成当前的字母组合。

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution:
def letterCombinations(self, digits: str) -> List[str]:
dict = {
'2': 'abc',
'3': 'def',
'4': 'ghi',
'5': 'jkl',
'6': 'mno',
'7': 'pqrs',
'8': 'tuv',
'9': 'wxyz'
}

res = [''] if digits else []

for digit in digits:
current_string = dict[digit]
current_res = []
for comb in res:
for letter in current_string:
current_res.append(comb + letter)
res = current_res

return res

这个问题还可以用递归来解

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
def letterCombinations(self, digits):
if not digits:
return []
dic = {"2":"abc", "3":"def", "4":"ghi", "5":"jkl", "6":"mno", "7":"pqrs", "8":"tuv", "9":"wxyz"}
res = []
self.dfs(digits, dic, 0, "", res)
return res

def dfs(self, digits, dic, index, path, res):
if len(path) == len(digits):
res.append(path)
return
for i in range(index, len(digits)):
for j in dic[digits[i]]:
self.dfs(digits, dic, i+1, path+j, res)