LeetCode: Letter Combinations of a Phone Number Posted on January 18, 2018July 26, 2020 by braindenny Letter Combinations of a Phone Number Similar Problems: LeetCode: Brace Expansion CheatSheet: Leetcode For Code Interview CheatSheet: Common Code Problems & Follow-ups Tag: #classic, #backtracking, #combination Given a digit string, return all possible letter combinations that the number could represent. A mapping of digit to letters (just like on the telephone buttons) is given below. Input:Digit string "23" Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]. Note: Although the above answer is in lexicographical order, your answer could be in any order you want. Github: code.dennyzhang.com Credits To: leetcode.com Leave me comments, if you have better ways to solve. Solution: // https://code.dennyzhang.com/letter-combinations-of-a-phone-number // Basic Ideas: backtracking // // Complexity: Time O(pow(3, N)*pow(4, M)), Space O(pow(3, N)*pow(4, M)) func dfs(combination string, digits string, pos int, m map[byte]string, res *[]string) { if pos == len(digits) { *res = append(*res, combination) return } for _, ch := range m[digits[pos]] { dfs(combination+string(ch), digits, pos+1, m, res) } } func letterCombinations(digits string) []string { res := []string{} if len(digits) == 0 { return res } m := map[byte]string{'2':"abc", '3':"def", '4':"ghi", '5':"jkl", '6':"mno", '7':"pqrs", '8':"tuv", '9':"wxyz"} dfs("", digits, 0, m, &res) return res } Post Views: 8