题目

电话号码的字母组合 - 图1

解题思路

哈希表存储每个数字对应的所有可能的字母。

DFS 递归深搜

代码

  1. class Solution {
  2. public List<String> letterCombinations(String digits) {
  3. List<String> combinations = new ArrayList<String>();
  4. if (digits.length() == 0) {
  5. return combinations;
  6. }
  7. Map<Character, String> phoneMap = Map.of(
  8. '2', "abc", '3', "def", '4', "ghi", '5', "jkl",
  9. '6', "mno", '7', "pqrs", '8', "tuv", '9', "wxyz"
  10. );
  11. backtrack(combinations, phoneMap, digits, 0, new StringBuffer());
  12. return combinations;
  13. }
  14. public void backtrack(List<String> combinations, Map<Character, String> phoneMap, String digits, int index, StringBuffer combination) {
  15. if (index == digits.length()) {
  16. combinations.add(combination.toString());
  17. } else {
  18. char digit = digits.charAt(index);
  19. String letters = phoneMap.get(digit);
  20. int lettersCount = letters.length();
  21. for (int i = 0; i < lettersCount; i++) {
  22. combination.append(letters.charAt(i));
  23. backtrack(combinations, phoneMap, digits, index + 1, combination);
  24. combination.deleteCharAt(index);
  25. }
  26. }
  27. }
  28. }