给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。
给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。
示例: 输入:"23" 输出:["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
这道题利用了回溯的思想,由于是不存在不可行的情况,直接穷举所有情况不需要剪枝操作。
package main import "fmt" var phoneMap map[string]string = map[string]string{ "2": "abc", "3": "def", "4": "ghi", "5": "jkl", "6": "mno", "7": "pqrs", "8": "tuv", "9": "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) { //tow is success if index == len(digits) { combinations = append(combinations, combination) } else { digit := string(digits[index]) letters := phoneMap[digit] lettersCount := len(letters) for i := 0; i < lettersCount; i++ { backtrack(digits, index + 1, combination + string(letters[i])) } } } func main(){ str := letterCombinations("23") for _,k :=range str{ fmt.Println(k) } }
很简单,不多说
时间复杂度:O(3^m+4^n) ,m为有三个字母的数字个数,n表示有四个字母的格式
空间复杂度:O(m+n)
参考地址:https://leetcode-cn.com/problems/letter-combinations-of-a-phone-number/solution/dian-hua-hao-ma-de-zi-mu-zu-he-by-leetcode-solutio/