题意:

image.png

解题思路:

  1. 思路:
  2. 1. 通过key找到对应的字母;
  3. 2. 递归拼接新字母;
  4. 3. 递归到目标长度,将当前字符串加入到数组中;

PHP代码实现:

  1. class Solution {
  2. public $res = [];
  3. public $str = "";
  4. public $array = [
  5. "2" => ["a","b","c"],
  6. "3" => ["d","e","f"],
  7. "4" => ["g","h","i"],
  8. "5" => ["j","k","l"],
  9. "6" => ["m","n","o"],
  10. "7" => ["p","q","r","s"],
  11. "8" => ["t","u","v"],
  12. "9" => ["w","x","y","z"],
  13. ];
  14. function letterCombinations($digits) {
  15. if (!$digits) return [];
  16. return $this->queue($digits, $step);
  17. $this->dfs($digits, 0);
  18. return $this->res;
  19. }
  20. function dfs($digits, $step) {
  21. if ($step == strlen($digits)) {
  22. $this->res[] = $this->str;
  23. return;
  24. }
  25. $key = substr($digits, $step, 1);
  26. $chars = $this->array[$key];
  27. foreach ($chars as $v) {
  28. $this->str .= $v;
  29. $this->dfs($digits, $step + 1);
  30. $this->str = substr($this->str, 0, strlen($this->str) - 1);
  31. }
  32. }
  33. function queue($digits, $step) {
  34. if (empty($digits)) return [];
  35. // 先创建字典
  36. $dic = ["0","1","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"];
  37. // 创建一个用于模拟队列的数组
  38. $resultList = [''];
  39. // 循环输入$digits
  40. for ($i = 0; $i < strlen($digits); $i++) {
  41. // 先获取当前$i对应的输入的字符串
  42. // 再使用intval 转成整形,用于根据键值对取对应的字符串
  43. $mapIndex = intval($digits[$i]);
  44. // 总是判断当前$resultList的第一个元素的字符长度是否等于当前$i
  45. while (strlen($resultList[0]) == $i) {
  46. // 将数组$resultList开头的单元移出数组
  47. $head = array_shift($resultList);
  48. $str = $dic[$mapIndex];
  49. for ($j = 0; $j < strlen($str); $j++) {
  50. $resultList[] = $head. $str[$j];
  51. }
  52. }
  53. }
  54. return $resultList;
  55. }
  56. }

GO代码实现:

  1. func letterCombinations(digits string) []string {
  2. if len(digits) == 0 {
  3. return []string{}
  4. }
  5. list := make([]byte, 0)
  6. result := make([]string, 0)
  7. backtrack(digits, 0, list, &result)
  8. return result
  9. }
  10. var table = map[byte][] byte {
  11. '2': []byte(`abc`),
  12. '3': []byte(`def`),
  13. '4': []byte(`ghi`),
  14. '5': []byte(`jkl`),
  15. '6': []byte(`mno`),
  16. '7': []byte(`pqrs`),
  17. '8': []byte(`tuv`),
  18. '9': []byte(`wxyz`),
  19. }
  20. func backtrack(s string, idx int, list []byte, result *[]string) {
  21. if idx == len(s) {
  22. *result = append(*result, string(list))
  23. return
  24. }
  25. c := table[s[idx]]
  26. for i := 0; i < len(c); i++ {
  27. list = append(list, c[i])
  28. backtrack(s, idx + 1, list, result)
  29. list = list[:len(list) - 1]
  30. }
  31. }