Letter Combinations of a Phone Number

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 public class Solution {
 2     public ArrayList<String> letterCombinations(String digits) {
 3         String[] str= {"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
 4         ArrayList<String> res = new ArrayList<String>();
 5         StringBuilder sb  = new StringBuilder ();
 6         DFS(digits,str,0,sb,res);
 7         return res;
 8     }
 9     public void DFS(String digits,String[]str,int start,StringBuilder sb,ArrayList<String>res){
10         if(start==digits.length()){
11             res.add(sb.toString());
12             return;
13         }
14         int d = digits.charAt(start)-'0';
15         for(int i=0;i<str[d].length();i++){
16             sb.append(str[d].charAt(i));
17             DFS(digits,str,start+1,sb,res);
18             sb.deleteCharAt(sb.length()-1);
19         }
20     }
21 }
View Code

 start  看成是第几个数字

 
posted @ 2014-02-06 05:30  krunning  阅读(276)  评论(0编辑  收藏  举报