leetcode17. Letter Combinations of a Phone Number

Posted godlei

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode17. Letter Combinations of a Phone Number相关的知识,希望对你有一定的参考价值。

题目描述:

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 }

 

以上是关于leetcode17. Letter Combinations of a Phone Number的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode算法题python解法:17. Letter Combinations of a Phone Number

Leetcode 17.——Letter Combinations of a Phone Number

LeetCode-17-Letter Combinations of a Phone Number

LeetCode17. Letter Combinations of a Phone Number

LeetCode17:Letter Combinations of a Phone Number

[LeetCode] 17. Letter Combinations of a Phone Number