ZhongKuo0228 / study

0 stars 0 forks source link

17. Letter Combinations of a Phone Number #113

Open fockspaces opened 11 months ago

fockspaces commented 11 months ago
  1. use backtracking method to record the string
  2. update the ans when it reach the end (digits is empty)
class Solution:
    letters = {
        "2": "abc",
        "3": "def",
        "4": "ghi",
        "5": "jkl",
        "6": "mno",
        "7": "pqrs",
        "8": "tuv",
        "9": "wxyz"
    }
    def letterCombinations(self, digits: str) -> List[str]:
        ans = []
        def helper(digits, string):
            if not digits:
                return ans.append(string) if string else None
            remaining_digits = digits[1:]
            for letter in self.letters[digits[0]]:
                helper(remaining_digits, string + letter)
        helper(digits, "")
        return ans