原题链接17. 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.
Example:
Input: “23”
Output: [“ad”, “ae”, “af”, “bd”, “be”, “bf”, “cd”, “ce”, “cf”].
解题思路:DFS算法参考了博客
func letterCombinations(digits string) []string {
var res []string = make([]string, 0, 64)
var keys []string = []string{" ", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}
if digits == "" {
return res
}
dfs(digits, keys, 0, "", &res)
return res
}
func dfs(graph string, colors []string, index int, path string, res *[]string) {
if index == len(graph) {
*res = append(*res, path)
return
}
actions := int(graph[index] - '0')
for _, v := range colors[actions] {
dfs(graph, colors, index+1, path+string(v), res)
}
}
相应BFS算法为:
func letterCombinations(digits string) []string {
var res []string = []string{}
var keys []string = []string{" ", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}
if digits == "" {
return res
}
res = append(res,"")
for _, d := range digits {
k := int(d - '0')
var seq []string
for _, v := range res {
for _, c := range keys[k] {
seq = append(seq, v+string(c))
}
}
res = seq
}
return res
}