3rd LeetCode: Letter Combinations of a Phone Number

Shu-Yu Huang
1 min readApr 16, 2020

Solution1

K digits form 2~9 represent a~z

Return all possible combinations of letters that that input K digits in the range of 2~9 can represent. For example, input 2 digits “45” could mean: ‘gj’, ‘gk’, ‘gl’, ‘hj’, ‘hk’, ‘hl’, ‘ij’, ‘ik’, ‘il’.

The solution is straight forward: decode each digit k for the possible letter(k)

  1. Create a function letter(digit) to produce possible letters for that digit:
    Map “2” to “abc”, ”3” to “def”, “4” to “ghi”,… and so on.
  2. Gain all possible letters according to input digits by function described in 1.
  3. Create a recursive function listing all the possible combination of letters (i.e., words):
    a. Pick one from each mapped letter sets generated by the digits and store this combination to the list.
    b. Try a different combination and store to the list, and so on.
  4. Return the list

https://leetcode.com/problems/letter-combinations-of-a-phone-number/discuss/602936/Python-3-recursive-mathod-with-code-mapping

--

--

Shu-Yu Huang

AI engineer in Taiwan AI Academy| Former process engineer in TSMC| Former Research Assistance in NYMU| Studying few-shot-learning and GAN