Leetcode - Symmetric Tree
Leetcode - Search Insert Position

Leetcode - Letter Combinations of a Phone Number

violet posted @ Jun 10, 2020 05:55:33 AM in 算法 with tags Algorithm Golang Recursive , 247 阅读

https://leetcode.com/problems/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.

A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.

 

func letterCombinations(digits string) []string {
    if len(digits) == 0 {
        return []string{}
    }
    hash := map[byte][]byte{
        '2': []byte{'a', 'b', 'c'},
        '3': []byte{'d', 'e', 'f'},
        '4': []byte{'g', 'h', 'i'},
        '5': []byte{'j', 'k', 'l'},
        '6': []byte{'m', 'n', 'o'},
        '7': []byte{'p', 'q', 'r', 's'},
        '8': []byte{'t', 'u', 'v'},
        '9': []byte{'w', 'x', 'y', 'z'},
    }
    result := []string{}
    combine(digits, hash, 0, "", &result)
    return result
}

func combine(digits string, hash map[byte][]byte, curr int, tmp string, result *[]string) {
    if curr ==  len(digits) {
        *result = append(*result, tmp)
        return
    }
    for _, c := range hash[digits[curr]] {
        combine(digits, hash, curr+1, tmp + string(c), result)
    }
}

登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter