zl程序教程

您现在的位置是:首页 >  其他

当前栏目

每日一题 --- 17. 电话号码的字母组合[力扣][Go]

2023-03-14 23:00:31 时间

题目:

给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。答案可以按 任意顺序 返回。

给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。

解题代码:

// 回溯法,深度优先算法 官方题解
var phoneMap = map[uint8]string{
    50: "abc",
    51: "def",
    52: "ghi",
    53: "jkl",
    54: "mno",
    55: "pqrs",
    56: "tuv",
    57: "wxyz",
}
var combinations []string
func letterCombinations(digits string) []string {
    if len(digits) == 0 {
        return []string{}
    }
    combinations = []string{}
    backtrack(digits, 0, "")
    return combinations
}
func backtrack(digits string, index int, combination string) {
    if index == len(digits) {
        combinations = append(combinations, combination)
    } else {
        digit := digits[index]
        letters := phoneMap[digit]
        lettersCount := len(letters)
        for i := 0; i < lettersCount; i++ {
            backtrack(digits, index + 1, combination + string(letters[i]))
        }
    }
}

这题也可以使用广度优先来实现

image