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.
Example:
Input: "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
题意
给一个电话键盘,数字对应相应的字母。给一个字符串,包含数字组合,给出相应的所有可能的字母组合。
思路
1.【模板题】求所有组合,考虑BFS或者DFS。
当拼接的字符串长度已经等于输入字符串长度,则保存起来,进入上一层循环。
- 遍历。
使用结果数组res表示遍历到当前的位置已有的结果,那么再遍历下一个位置的时候,把这个位置能形成的所有结果和原来的进行两两组合。
代码
class Solution:
def letterCombinations(self, digits):
def dfs(num, string, res):
if num == length:
res.append(string)
return
for cur in dict[digits[num]]:
dfs(num + 1, string + cur, res)
dict = {'2': ['a', 'b', 'c'],
'3': ['d', 'e', 'f'],
'4': ['g', 'h', 'i'],
'5': ['j', 'k', 'l'],
'6': ['m', 'n', 'o'],
'7': ['p', 'q', 'r', 's'],
'8': ['t', 'u', 'v'],
'9': ['w', 'x', 'y', 'z']
}
length = len(digits)
if length == 0:
return []
res = []
dfs(0, "", res)
return res
def letterCombinations2(self, digits):
if digits == "":
return []
dict = {'2': ['a', 'b', 'c'],
'3': ['d', 'e', 'f'],
'4': ['g', 'h', 'i'],
'5': ['j', 'k', 'l'],
'6': ['m', 'n', 'o'],
'7': ['p', 'q', 'r', 's'],
'8': ['t', 'u', 'v'],
'9': ['w', 'x', 'y', 'z']
}
res = [""]
for cur in digits:
res = [w + c for c in dict[cur] for w in res]
return res
网友评论