题目
给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。
给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。
链接: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.
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”].
思路及代码
DFS
class Solution:
def letterCombinations(self, digits: str) -> List[str]:
d = [[],[],
['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']]
cur = []
ans = []
def dfs(pos, cur, ans):
if pos == len(digits):
if cur:
ans.append("".join(cur))
return
digit = int(digits[pos])
for i in range(len(d[digit])):
cur.append(d[digit][i])
dfs(pos+1, cur, ans)
cur.pop()
dfs(0, cur, ans)
return ans