赞
踩
给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。答案可以按 任意顺序 返回。
给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。
示例 1:
输入:digits = “23”
输出:[“ad”,“ae”,“af”,“bd”,“be”,“bf”,“cd”,“ce”,“cf”]
示例 2:
输入:digits = “”
输出:[]
示例 3:
输入:digits = “2”
输出:[“a”,“b”,“c”]
提示:
例如示例 1:
class Solution:
def letterCombinations(self, digits: str) -> List[str]:
digitsLen = len(digits)
if digitsLen == 0:
return []
digitWord = {"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"]}
newList = digitWord[digits[0]]
for i in range(1, digitsLen):
tmpList = list()
for k in digitWord[digits[i]]:
for j in newList:
j += k
tmpList.append(j)
newList = tmpList[:]
return newList
看了下 腐烂的橘子 的题解 回溯+队列 图解,感觉还挺麻烦,之后研究下。
class Solution: def letterCombinations(self, digits: str) -> List[str]: if not digits: return [] phone = {'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']} def backtrack(conbination,nextdigit): if len(nextdigit) == 0: res.append(conbination) else: for letter in phone[nextdigit[0]]: backtrack(conbination + letter,nextdigit[1:]) res = [] backtrack('',digits) return res
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。