电话号字母组合,利用深度搜索的思想。

Given a digit string, 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.

Input:Digit string "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].

 1 import java.util.ArrayList;
 2 import java.util.List;
 3 
 4 public class test
 5 {
 6           List<String> res;
 7         public List<String> letterCombinations(String digits) {
 8             String[] table = {"","", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
 9             char[] temp = new char[digits.length()];
10             res = new ArrayList<String>();
11             helper(table, 0, temp, digits);
12             return res;
13         }
14         
15         public void helper(String[] table, int index, char[] temp, String digits)
16         {
17             if(index == digits.length())
18             {
19                 if(temp.length!=0)//判断,不然A不过去。
20                 {
21                     res.add(new String(temp));
22                 }
23             }
24             else
25             {
26                 String candidates = table[digits.charAt(index)-'0'];//候选字母表
27                 for(int i = 0; i < candidates.length(); i ++)
28                 {
29                     temp[index] = candidates.charAt(i);
30                     helper(table, index + 1, temp, digits);//深度遍历digits
31                 }
32             }
33         }
34         
35         public static void main(String[] args)
36         {
37             test t = new test();
38             System.out.println(t.letterCombinations("23"));
39         }
40 }

 

posted @ 2016-05-27 19:31  32ddd  阅读(426)  评论(0编辑  收藏  举报