力扣的电话号码的字母组合解法
题目描述:
给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。
给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。
示例:
输入:“23”
输出:[“ad”, “ae”, “af”, “bd”, “be”, “bf”, “cd”, “ce”, “cf”].
说明:
尽管上面的答案是按字典序排列的,但是你可以任意选择答案输出的顺序。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/letter-combinations-of-a-phone-number
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
参考程序1:
class Solution:
def letterCombinations(self, digits: str) -> List[str]:
dic={'2':"abc",'3':"def",'4':"ghi",'5':"jkl",'6':"mno",'7':"pqrs",'8':"tuv",'9':"wxyz"}
result=[]
for i in digits:
temp=[]
if len(result)==0:
for j in range(len(dic[i])):
temp.append(dic[i][j])
else:
for j in range(len(dic[i])):
for k in result:
temp.append(k+dic[i][j])
result=temp
return result
运行结果1:
参考程序2:
class Solution:
def letterCombinations(self, digits: str) -> List[str]:
dic={'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']}
result = []
temp = []
len_digits = len(digits)
if len_digits == 0:
return temp
if len_digits == 1:
return dic[digits]
temp= self.letterCombinations(digits[1:])
for i in dic[digits[0]]:
for j in temp:
result.append(i+j)
return result
运行结果2:
参考程序3:
class Solution:
def letterCombinations(self, digits: str) -> List[str]:
num_d = {}
num_d[2] = ['a','b','c']
num_d[3] = ['d','e','f']
num_d[4] = ['g','h','i']
num_d[5] = ['j','k','l']
num_d[6] = ['m','n','o']
num_d[7] = ['p','q','r','s']
num_d[8] = ['t','u','v']
num_d[9] = ['w','x','y','z']
if len(digits) == 0:
return []
if len(digits) == 1:
return num_d[int(digits)]
else:
c_ans = self.letterCombinations(digits[1:])
b_ans = []
for ch in num_d[int(digits[0])]:
for a in c_ans:
b_ans.append(ch+a)
return b_ans
return result
运行结果3:
来源:CSDN
作者:chutu2018
链接:https://blog.csdn.net/chutu2018/article/details/104760175