17.go 811 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. package main
  2. import (
  3. "fmt"
  4. )
  5. var mBtn = map[byte][]string{
  6. '2': {"a", "b", "c"},
  7. '3': {"d", "e", "f"},
  8. '4': {"g", "h", "i"},
  9. '5': {"j", "k", "l"},
  10. '6': {"m", "n", "o"},
  11. '7': {"p", "q", "r", "s"},
  12. '8': {"t", "u", "v"},
  13. '9': {"w", "x", "y", "z"},
  14. }
  15. func letterCombinationsIter(digits string, last []string) []string {
  16. if len(digits) == 0 {
  17. return last
  18. }
  19. res := make([]string, 0)
  20. char := mBtn[digits[0]]
  21. for _, v := range last {
  22. for _, c := range char {
  23. res = append(res, v+c)
  24. }
  25. }
  26. return letterCombinationsIter(digits[1:], res)
  27. }
  28. func letterCombinations(digits string) []string {
  29. if len(digits) == 0 {
  30. return []string{}
  31. }
  32. return letterCombinationsIter(digits[1:], mBtn[digits[0]])
  33. }
  34. func main() {
  35. fmt.Println(letterCombinations("23"))
  36. fmt.Println(letterCombinations("234"))
  37. }