leetcode 17. 电话号码的字母组合

题解

递归,首先把digits中的每一个数字,依次转化为相对应的字符串存入strings数组中,然后依次递归遍历strings[0], strings[1]...strings[n]

示例代码(go)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
func letterCombinations(digits string) []string {
res := make([]string, 0)
arr := []string{"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}
if digits == "" {
return res
}
strings := make([]string, len(digits))
for i, v := range digits {
strings[i] = arr[v-'2']
}
recursion(strings, &res, "")

return res
}

func recursion(strings []string, res *[]string, str string) {
if len(strings) == 0 {
*res = append(*res, str)
return
}
for _, v := range strings[0] {
recursion(strings[1:], res, str+string(v))
}
}