thiagowfx's avatar

Β¬ just serendipity πŸ€ (not just serendipity)

LeetCode #17: Letter Combinations of a Phone Number

β€’ 60 words β€’ 1 min β€’ updated

LeetCode #17: Letter Combinations of a Phone Number:

python
class Solution:
    def letterCombinations(self, digits: str) -> List[str]:

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

        ans = []

        def backtrack(candidate, digits):
            if not digits:
                ans.append(candidate)
                return

            for letter in m[digits[0]]:
                backtrack(candidate + letter, digits[1:])


        backtrack("", digits)

        return ans