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"]. Note: Although the above answer is in lexicographical order, your answer could be in any order you want.
My code:
import numpy as np
class Solution:
def letterCombinations(self, digits):
"""
:type digits: str
:rtype: List[str]
"""
record=[]
for i in range(len(digits)):
if digits[i]=='2':
tmp_record=[]
tmp_record.append('a')
tmp_record.append('b')
tmp_record.append('c')
record.append(tmp_record)
elif digits[i]=='3':
tmp_record=[]
tmp_record.append('d')
tmp_record.append('e')
tmp_record.append('f')
record.append(tmp_record)
elif digits[i]=='4':
tmp_record=[]
tmp_record.append('g')
tmp_record.append('h')
tmp_record.append('i')
record.append(tmp_record)
elif digits[i]=='5':
tmp_record=[]
tmp_record.append('j')
tmp_record.append('k')
tmp_record.append('l')
record.append(tmp_record)
elif digits[i]=='6':
tmp_record=[]
tmp_record.append('m')
tmp_record.append('n')
tmp_record.append('o')
record.append(tmp_record)
elif digits[i]=='7':
tmp_record=[]
tmp_record.append('p')
tmp_record.append('q')
tmp_record.append('r')
tmp_record.append('s')
record.append(tmp_record)
elif digits[i]=='8':
tmp_record=[]
tmp_record.append('t')
tmp_record.append('u')
tmp_record.append('v')
record.append(tmp_record)
elif digits[i]=='9':
tmp_record=[]
tmp_record.append('w')
tmp_record.append('x')
tmp_record.append('y')
tmp_record.append('z')
record.append(tmp_record)
#print(record)
output=[]
out=self.recursive(record,output,0)
return out
def recursive(self,record,output,start):
#print('executing %d time'%start)
#print(output)
if start==len(record):
return output
if start==0:
tmp_record=record[start]
for i in range(len(tmp_record)):
output.append(tmp_record[i])
start+=1
return self.recursive(record,output,start)
else:
new_output=[]
for item in output:
tmp_record=record[start]
for i in range(len(tmp_record)):
str_out=item+tmp_record[i]
new_output.append(str_out)
#output=new_output
start+=1
return self.recursive(record,new_output,start)
Solution:
https://leetcode.com/problems/letter-combinations-of-a-phone-number/