17.电话号码的字母组合
17.电话号码的字母组合
题解
题目:一个数字对应几个字母,求一串数字,返回数字能够组合的字符串
思路:像这种题一看就是dfs回溯,代码一看就懂了,不解释了
代码
func letterCombinations(digits string) []string { if digits == "" { return nil } mp := map[string]string{ "2": "abc", "3": "def", "4": "ghi", "5": "jkl", "6": "mno", "7": "pqrs", "8": "tuv", "9": "wxyz", } n := len(digits) result := make([]string, 0) var dfs func(digits string, cur string) dfs = func(digits string, cur string) { if len(cur) == n { result = append(result, cur) return } ch := string(digits[0]) cnt := mp[ch] for _, letter := range cnt { dfs(digits[1:], cur+string(letter)) } } dfs(digits, "") return result }