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.
这道题很像之前我们解决的Subset和Permutaion排列组合的题,所以用起dfs也很直观。
为了方便我们按照电话上的按键创造一个字符矩阵 Char[ ][ ] table, 用来存储电话按键的字符,用按键的数字做行,里面的字符做列,这样取起来比较容易。每次我们取digits的第一位字符,然后进入它所在矩阵的那一行做从 i = 0 -> 结尾的搜索,在取完这一位字符的时候,传入下一层递归时候我们传入除去第一位剩下的String。这样做的好处为,我们可以固定的取第一位字符,而且添加进res的条件也很直观,一直到digits的长度为0为止。
public class Solution {
public ArrayList<String> letterCombinations(String digits) {
char[][] table = {{},{'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'}};
ArrayList<String> res = new ArrayList<String>();
dfs(digits,table,"",res);
return res;
}
public void dfs(String digits, char[][] table, String tmp, ArrayList<String> res){
if (digits.length()==0){
res.add(tmp);
return;
}
for(int i=0; i<table[digits.charAt(0) - '0' - 1].length;i++)
dfs(digits.substring(1),table,tmp+table[digits.charAt(0)-'0'-1][i],res);
}
}
几点注意的地方:
1. 数字1所对应的是空集,不要忘了
2. char字符转换成数字 digits.charAt(0) - '0' - 1, 减去'0'是为了转换成int,再减去1是为了找到对应的行
3. tmp直接添加字符传入递归参数,这样返回后不用截取tmp