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.
Example 1:
Input: digits = "23"
Output: ["ad","ae","af","bd","be","bf","cd","ce","cf"]
Example 2:
Input: digits = ""
Output: []
Example 3:
Input: digits = "2"
Output: ["a","b","c"]
Constraints:
0 <= digits.length <= 4
digits[i] is a digit in the range [‘2’, ‘9’].
解释
题目意思:一个数字对应几个字母,一串数字对应的字符串可以有多少种?
总结
我看leetcode 上的答案是用backtacking 解的。 为了思维简单,我直接用bfs 解了。 迭代输入字符串,访问到新的数字时,在上一层的基础上再组合新的组合。
python code
class Solution(object):
def letterCombinations(self, digits):
"""
:type digits: str
:rtype: List[str]
"""
hash = {
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'],
}
ans = []
numbers = list(digits)
numbers = [int(s) for s in numbers ]
for n in numbers:
if not ans:
ans = hash[n]
else:
temp = ans
ans = []
for s in temp:
for c in hash[n]:
ans.append(s + c)
return ans
2021 七月十四, 旧金山,晴l