17. Letter Combinations of a Phone Number

Given a string containing digits from 2-9 inclusive, 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. Note that 1 does not map to any letters.

Example:

Input: "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 class Solution {
 2     public char [][] dist;
 3     public int []num;
 4     public void dfs(char[] now, int pos, List<String> ans, String digits) {
 5         if (pos == digits.length()) {
 6             char[] temp = new char[pos];
 7             for (int i = 0; i < pos; ++i)
 8                 temp[i] = now[i];
 9             ans.add(String.valueOf(temp));
10             return;
11         }
12         char c = digits.charAt(pos);
13         int id = c - '2';
14         for (int i = 0; i < num[id]; ++i) {
15             now[pos] = dist[id][i];
16             dfs(now, pos + 1, ans, digits);
17         }
18         
19         
20     }
21     
22     public void init() {
23         int []temp = new int[]{3, 3, 3, 3, 3, 4, 3, 4};
24         dist = new char[8][5];
25         int sum = 0;
26         for (int i = 0; i < 8; ++i) {
27             sum += i== 0 ? 0 : temp[i - 1];
28             for (int j = 0; j < temp[i]; ++j) {
29                 dist[i][j] = (char)(j  + 97 + sum);
30             }
31         }
32         num = temp;
33     }
34     public List<String> letterCombinations(String digits) {
35         List<String> ans = new ArrayList<>();
36         if (digits.length() == 0) return ans;
37         int n = digits.length();
38         char []now = new char[n + 1];
39         init();
40        
41         
42         dfs(now, 0, ans, digits);
43         return ans;
44     }
45 }

 

posted @ 2020-02-13 19:12  hyx1  阅读(123)  评论(0编辑  收藏  举报