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.
题解:用一个二维数组map保存数字到字母的映射,然后深度优先递归搜索如下的一棵树(以"23"为例,树不完整)
代码如下:
1 public class Solution { 2 public ListletterCombinations(String digits) { 3 ArrayList answer = new ArrayList (); 4 5 char[][] map = { {'a','b','c'},{'d','e','f'},{'g','h','i'},{'j','k','l'},{'m','n','o'},{'p','q','r','s'},{'t','u','v'},{'w','x','y','z'}}; 6 String currentPath = new String(); 7 8 DeepSearch(map, answer, digits, currentPath); 9 return answer;10 }11 12 public void DeepSearch(char[][] map,List answer,String digits,String currentPath){13 if(digits.length() == 0)14 {15 String temp = new String(currentPath);16 answer.add(temp);17 18 return;19 }20 21 int now = digits.charAt(0) - '0';22 for(int j = 0;j < map[now-2].length;j++){23 currentPath += map[now-2][j];24 DeepSearch(map, answer, digits.substring(1), currentPath);25 currentPath = currentPath.substring(0, currentPath.length()-1);26 }27 }28 }