跳转至

LC17 - 电话号码的字母组合

LetterCombinations.go
package Backtrack

var hashMap map[int]string

func initMap() {
    hashMap = make(map[int]string)
    hashMap[2] = "abc"
    hashMap[3] = "def"
    hashMap[4] = "ghi"
    hashMap[5] = "jkl"
    hashMap[6] = "mno"
    hashMap[7] = "pqrs"
    hashMap[8] = "tuv"
    hashMap[9] = "wxyz"
}

func letterCombinations(digits string) []string {
    if digits == "" {
        return nil
    }
    initMap()
    result := make([]string, 0)
    size := len(digits)
    var path string
    var f func(i int)
    f = func(i int) {
        if i == size {
            result = append(result, path)
            return
        }
        curSet := hashMap[int(digits[i]-'0')]
        for _, ch := range curSet {
            path += string(ch)
            f(i + 1)
            path = path[:len(path)-1]
        }
    }
    f(0)
    return result
}