Letter combinations of a Phone number
Given a digit string, return all possible letter combinations this number could represent.
A mapping of Digit to letters (just as the telephone buttons) is given below.
Input:digit string "23"
Output: ["Ad", "AE", "AF", "BD", "Be", "BF", "CD", "CE", "CF"].
The picture is not on the phone, meaning that the 9 House button, 2 corresponding to the abc,3 corresponding Def, so. To give you all the possibilities, it's mathematically called, I forgot ...
is to use recursion or DFS, such as give ' 234 ', first look at 2, that should now be [' A ', ' B ', ' C '],
Plus 3, is it not on the basis of this [' A ', ' B ', ' C '], [' A ', ' B ', ' C '] each followed by a ' d ', ' e ', ' F ': that is, ["Ad", "AE", "AF", "BD", "Be", "BF", " CD ", ce", "CF"],
Then add 4 ' g ' h ' I ', and so on.
Here is the Python implementation, which is cool, the main recursive function on one line. Do not know how many C + + line Ah ...
class Solution (object): Def lettercombinations (self, digits): "" ": Type Digi TS:STR:RTYPE:LIST[STR] "" if digits = = ': return [] self.
Digitdict=[', ' 1 ', ' abc ', ' Def ', ' Ghi ', ' jkl ', ' mno ', ' PQRS ', ' TUV ', ' wxyz '] res = ['] for D in digits:
res = SELF.LETTERCOMBBT (int (d), Res) return res def LETTERCOMBBT (self, digit, oldstrlist): return [dstr+i to I in self. Digitdict[digit] for dstr in Oldstrlist]