【Description】
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.
imageExample:
Input: "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
【Idea】
base解法的逻辑性要求不是很高,主要是代码实现的两点trick:
- 数字到字符的映射,定义list: ['', '', 'abc', 'def', 'ghi', 'jkl', 'mno', 'pqrs', 'tuv', 'wxyz'] 将数字以下标形式表示;
- result = [ori_str+i for i in digit_str[int(temp_num)] for ori_str in result] 实现嵌套循环。
【Solution】
class Solution:
def letterCombinations(self, digits):
if digits == "":
return []
digit_str = ['', '', 'abc', 'def', 'ghi', 'jkl', 'mno', 'pqrs', 'tuv', 'wxyz']
result = ['']
for temp_num in digits:
result = [ori_str+i for i in digit_str[int(temp_num)] for ori_str in result]
return result
网友评论