17. Letter Combinations of a Phone Number

题目链接:https://leetcode.com/problems/letter-combinations-of-a-phone-number/description/

题目大意:给出所给数字所对应字母的所有组合字符串。例子如下:

解法一:深搜,没遇到一个数字,就dfs一次它所对应的字母,然后再回溯,基本上就是组合的排列组合的变形。细节注意:1.将每个数字所对应的字符串存入数组。2.将字符数字转为数字。3.删除字符串最后一个字符。代码如下(耗时3ms):

 1     private static String[] s = {"", "", "abc", "def", "ghi", "jkl", "mno", "qprs", "tuv", "wxyz"};//1.将每个数字所对应的字符串存入数组。
 2     public List<String> letterCombinations(String digits) {
 3         List<String> res = new ArrayList<String>();
 4         if(digits.length() == 0) {
 5             return res;
 6         }
 7         String listIn = "";
 8         dfs(digits, res, listIn, 0);
 9         return res;
10     }
11     public static void dfs(String digits, List<String> res, String listIn, int index) {
12         if(listIn.length() == digits.length()) {
13             res.add(new String(listIn));
14         }
15         if(index == digits.length()) {
16             return;
17         }
18         int pos = digits.charAt(index) - '0';//2.将字符数字转为数字。
19         int length = s[pos].length();
20         for(int i = 0; i < length; i++) {
21             listIn += s[pos].charAt(i);
22             dfs(digits, res, listIn, index + 1);
23             listIn = listIn.substring(0, listIn.length() - 1);//3.删除字符串最后一个字符。
24         }
25     }
View Code

 

posted on 2018-01-22 15:56  二十年后20  阅读(185)  评论(0编辑  收藏  举报

导航