码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2016-05-27 20:20:37      阅读:143      评论:0      收藏:0      [点我收藏+]

标签:

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 }

 

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

标签:

原文地址:http://www.cnblogs.com/masterlibin/p/5535805.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!