categories: leetcode


初步了解回溯算法

题目描述

Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent.
A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.
17. Letter Combinations of a Phone Number - 图1
Example: Input: “23” Output: [“ad”, “ae”, “af”, “bd”, “be”, “bf”, “cd”, “ce”, “cf”].Note:
Although the above answer is in lexicographical order, your answer could be in any order you want.

参考代码

  1. class Solution {
  2. public List<String> letterCombinations(String digits) {
  3. if (digits.length() != 0) backtrack("",digits);
  4. return output;
  5. }
  6. Map<String, String> phone = new HashMap<String, String>() {{
  7. put("2", "abc");
  8. put("3", "def");
  9. put("4", "ghi");
  10. put("5", "jkl");
  11. put("6", "mno");
  12. put("7", "pqrs");
  13. put("8", "tuv");
  14. put("9", "wxyz");
  15. }};
  16. List<String> output = new ArrayList<String>();
  17. public void backtrack(String combination, String next_digits) {
  18. if (next_digits.length() == 0) {
  19. //意味着一条分支走到底,譬如 adg
  20. output.add(combination);
  21. }else {
  22. String digit = next_digits.substring(0, 1);
  23. String letters = phone.get(digit);
  24. for (int i = 0; i < letters.length(); i++) {
  25. //分割回溯
  26. String letter = phone.get(digit).substring(i, i + 1);
  27. backtrack(combination + letter, next_digits.substring(1));
  28. }
  29. }
  30. }
  31. }

思路及总结

首先题目描述最好还是加上不允许重复,还有就是几个数字对应几个字母组合。。。。
回溯是一种通过探索所有潜在候选者来查找所有解决方案的算法。如果候选解决方案变为不是解决方案(或者至少不是最后一个解决方案),则回溯算法通过在前一步骤上进行一些更改(即回溯然后再次尝试)来丢弃它。
我怎么感觉更像 DFS 呢。。。。就是递归然后进行组合,回溯可能考虑的是得到 adg,还要回去得到 adh

参考

https://leetcode.com/problems/letter-combinations-of-a-phone-number/solution/