Skip to content

Prepare For Coder Interview – Denny

  • Basic
  • Medium
  • Hard
  • Architect
  • Life

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.

Leetcode: Letter Combinations of a Phone Number

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
}
linkedin
github
slack

Post Views: 8
Posted in BasicTagged #backtracking, #classic, #combination

Post navigation

LeetCode: Third Maximum Number
LeetCode: Number of Boomerangs

Leave a Reply Cancel reply

Your email address will not be published.

Tags

#array #backtracking #bfs #binarytree #bitmanipulation #blog #classic #codetemplate #combination #dfs #dynamicprogramming #game #graph #greedy #heap #inspiring #interval #linkedlist #manydetails #math #palindrome #recursive #slidingwindow #stack #string #subarray #trie #twopointer #twosum binarysearch editdistance hashmap intervaldp knapsack monotone oodesign presum rectangle redo review rotatelist series sql treetraversal unionfind

Recent Posts

  • a
  • a
  • a
  • a
  • a

Recent Comments

    Archives

    Categories

    • Amusing
    • Basic
    • Easy
    • Hard
    • Life
    • Medium
    • Resource
    • Review
    • Series
    • Uncategorized
    Proudly powered by WordPress | Theme: petals by Aurorum.