题目描述:

Given a digit string, return all possible letter combinations that the number could represent.

解题分析:

回溯法的典型应用,用一个数据结构表示出按键与其表示字母的对应关系,直接用回溯法做即可。

具体代码:

 1 public class Solution {
 2     private static List<String> results=new ArrayList<String>();
 3     private static String[] array= {"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
 4     public static List<String> letterCombinations(String digits) {
 5             //String[] array= {"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
 6             results=new ArrayList<String>();
 7             if(digits==null||digits.length()==0)
 8                 return results;
 9             StringBuilder sb = new StringBuilder();
10             
11             fun(digits,sb,0);
12             return results;
13     }
14 
15     private static void fun(String digits, StringBuilder sb,
16             int i) {
17         if(i==digits.length()-1){
18             char ch = digits.charAt(i);
19             int index = ch-'0';
20             for(int j=0;j<array[index].length();j++){
21                 sb.append(array[index].charAt(j));
22                 results.add(sb.toString());
23                 sb.deleteCharAt(sb.length()-1);
24             }
25             return;
26         }
27         char ch = digits.charAt(i);
28         int index = ch-'0';
29         for(int j=0;j<array[index].length();j++){
30             sb.append(array[index].charAt(j));
31             fun(digits, sb, i+1);
32             sb.deleteCharAt(sb.length()-1);
33         }
34     }
35 }

 

相关文章:

  • 2021-07-30
  • 2022-01-25
  • 2022-02-20
  • 2022-01-28
  • 2021-09-04
  • 2022-12-23
猜你喜欢
  • 2021-05-11
  • 2021-06-09
  • 2021-06-12
  • 2022-02-04
  • 2021-06-21
  • 2022-02-01
  • 2021-08-07
  • 2021-10-07
相关资源
相似解决方案