17. Letter Combinations of a Phone Number

Medium question

Table of contents

Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. Return the answer in any order.

A mapping of digits to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.

Example 1:

Input: digits = "23"
Output: ["ad","ae","af","bd","be","bf","cd","ce","cf"]

Example 2:

Input: digits = ""
Output: []

Example 3:

Input: digits = "2"
Output: ["a","b","c"]

Constraints:

  • 0 <= digits.length <= 4

  • digits[i] is a digit in the range ['2', '9'].


Solution

class Solution:
    def letterCombinations(self, digits: str) -> List[str]:
        two=["a","b","c"]
        three=["d","e","f"]
        four=["g","h","i"]
        five=["j","k","l"]
        six=["m","n","o"]
        sev=["p","q","r","s"]
        eit=["t","u","v"]
        nin=["w","x","y","z"]
        hs={2:two,3:three,4:four,5:five,6:six,7:sev,8:eit,9:nin}
        res=[]
        if len(digits)<1:
            return res
        elif len(digits)==1:
            for i in hs[int(digits)]:
                res.append(i)
        elif len(digits)==2:
            for i in hs[int(digits[0])]:
                for j in hs[int(digits[1])]:
                    res.append(i+j)
        elif len(digits)==3:
            for i in hs[int(digits[0])]:
                for j in hs[int(digits[1])]:
                    for m in hs[int(digits[2])]:
                        res.append(i+j+m)
        elif len(digits)==4:
            for i in hs[int(digits[0])]:
              for j in hs[int(digits[1])]:
                for m in hs[int(digits[2])]:
                  for n in hs[int(digits[3])]:
                    res.append(i+j+m+n)
        return res