首页 > 其他 > 详细

【leetcode】17. Letter Combinations of a Phone Number

时间:2016-07-05 00:59:23      阅读:240      评论:0      收藏:0      [点我收藏+]

题目描述:

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 }

 

【leetcode】17. Letter Combinations of a Phone Number

原文:http://www.cnblogs.com/godlei/p/5642142.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!