17. Letter Combinations of a Phone Number

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.


def letterCombinations(digits: str) -> List[str]:

    m = {"2": "abc", "3": "def", "4": "ghi", "5": "jkl",
        "6": "mno", "7": "pqrs", "8": "tuv", "9": "wxyz"}    

    if not digits:
        return []    

    combs = []
   
    def recurse(pos, cur):
       
        if pos == len(digits):
            combs.append(cur)
            return
       
        digit = digits[pos]
        letters = m[digit]
        for l in letters:
            recurse(pos+1, cur+l)
           
    recurse(0, "")    

    return combs

Comments

Popular posts from this blog

849. Maximize Distance to Closest Person

347. Top K Frequent Elements

139. Word Break