Letter Combinations of a Phone Number

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

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

参考:http://www.cnblogs.com/tgkx1054/p/3298501.html

度娘过后,发现很多人用的都是dfs递归实现的,当然直接贴代码的还是很多,我也是这样的。

 1 import java.util.ArrayList;
 2 import java.util.Arrays;
 3 import java.util.List;
 4 
 5 public class Solution {
 6     List<String> result = new ArrayList<String>();
 7     String dict[] = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
 8     String path = "";
 9     
10     public List<String> letterCombinations(String digits) {
11         dfs(digits);
12         
13         return result;
14     }
15     
16     /**
17      * 这里用dfs来解决
18      * @param dep
19      * @param digits
20      */
21     public void dfs(String digits){
22         if(digits.length() == 0){
23             result.add(path);
24         }else{
25             for(int i = 0; i < dict[digits.charAt(0) - '0'].length(); i++){
26                 path += dict[digits.charAt(0) - '0'].charAt(i);
27                 dfs(digits.substring(1, digits.length()));
28                 path = path.substring(0, path.length() - 1);
29             }
30         }
31     }
32 }

 

posted on 2014-12-09 20:54  luckygxf  阅读(175)  评论(0编辑  收藏  举报

导航