17. Letter Combinations of a Phone Number java solutions

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"].

Note:
Although the above answer is in lexicographical order, your answer could be in any order you want.

 

 1 public class Solution {
 2     public List<String> letterCombinations(String digits) {
 3         List<String> ans = new ArrayList<String>();
 4         if("".equals(digits) || digits == null) return ans;
 5         String[] numTochar = {"", "", "abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
 6         Combinations(ans,0,digits,"",numTochar);
 7         return ans;
 8     }
 9     
10     public void Combinations(List<String> ans, int s,String digits, String tmp,String[] numTochar){
11         if(s == digits.length()){
12             ans.add(new String(tmp));
13             return;
14         }
15         //for(int i = s; i < digits.length();i++){第一遍想错了,多了个循环 。一直AC不了
16             int index = digits.charAt(s) - '0';
17             for(int j = 0; j < numTochar[index].length(); j++){
18                 Combinations(ans,s+1,digits,tmp + numTochar[index].charAt(j),numTochar);
19             }
20        // }
21     }
22 }

 

posted @ 2016-06-29 09:59  Miller1991  阅读(189)  评论(0编辑  收藏  举报