Letter Combinations of a Phone Number

Description

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"].

输入九宫格输入法数字,输出对应的所有字母组合

Solution

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
func letterCombinations(digits string) []string {
    if len(digits) < 1 {
        return []string{}
    }

    if len(digits) == 1 {
        switch digits {
        case "2":
            return []string{"a", "b", "c"}
        case "3":
            return []string{"d", "e", "f"}
        case "4":
            return []string{"g", "h", "i"}
        case "5":
            return []string{"j", "k", "l"}
        case "6":
            return []string{"m", "n", "o"}
        case "7":
            return []string{"q", "p", "r", "s"}
        case "8":
            return []string{"t", "u", "v"}
        case "9":
            return []string{"w", "x", "y", "z"}
        case "0":
            return []string{" "}
        default:
            return []string{""}
        }
    }

    r := make([]string, 0)

    for _, front := range letterCombinations(digits[:1]) {
        for _, back := range letterCombinations(digits[1:]) {
            r = append(r, front+back)
        }
    }

    return r
}