#-*-Coding:utf8-*-
‘‘‘
__author__ = ' [email protected] '
17:letter combinations of a Phone number
https://oj.leetcode.com/problems/letter-combinations-of-a-phone-number/
Given a digit string, return all possible letter combinations, the number could represent.
A mapping of Digit to letters (just as on the telephone buttons) is given below.
Input:digit string "23"
Output: ["Ad", "AE", "AF", "BD", "Be", "BF", "CD", "CE", "CF"].
===comments by dabay===
Compare a typical recursive call.
Each time a word is digested, the corresponding letter is the Cartesian product of the existing string.
‘‘‘
Class Solution:
# @return A list of strings, [S1, S2]
def lettercombinations (self, digits):
def letterCombinations2 (digits, strings, D):
If len (digits) = = 0:
return strings
Letters = D[digits[0]]
New_strings = []
For letters:
For i in Xrange (Len (Strings)):
New_strings.append (Strings[i] + letter)
Return LetterCombinations2 (digits[1:], new_strings, D)
D = {}
d["0"] = d["1"] = ""
d["2"] = "abc"
d["3"] = "def"
d["4"] = "Ghi"
d["5"] = "JKL"
d["6"] = "MNO"
d["7"] = "PQRS"
d["8"] = "TUV"
d["9"] = "WXYZ"
return letterCombinations2 (digits, [""], D)
def main ():
Sol = solution ()
Print sol.lettercombinations ("23")
if __name__ = = "__main__":
Import time
Start = Time.clock ()
Main ()
Print "%s sec"% (Time.clock ()-start)
[Leetcode] [Python]17:letter combinations of a Phone number