425 · 电话号码的字母组合
描述
给一个不包含0和1的数字字符串,每个数字代表一个字母,请返回其所有可能的字母组合。
下图的手机按键图,就表示了每个数字可以代表的字母。
1 2
ABC 3
DEF
4
GHI 5
JKL 6
MNO
7
PQRS 8
TUV 9
WXYZ
以上的答案是按照词典编撰顺序进行输出的,不过,在做本题时,你也可以任意选择你喜欢的输出顺序。
样例
样例 1:
输入: “23”
输出: [“ad”, “ae”, “af”, “bd”, “be”, “bf”, “cd”, “ce”, “cf”]
解释:
‘2’ 可以是 ‘a’, ‘b’ 或 ‘c’
‘3’ 可以是 ‘d’, ‘e’ 或 ‘f’
样例 2:
输入: “5”
输出: [“j”, “k”, “l”]
public class Solution {
/**
* @param digits: A digital string
* @return: all posible letter combinations
*/
public List<String> letterCombinations(String digits) {
// write your code here
String[] phone = {" " , " " , "abc", "def" , "ghi" , "jkl" , "mno" , "pqrs" , "tuv" , "wxyz"} ;
List<String> ans = new ArrayList<>() ;
int n = digits.length();
if(digits == null || n == 0){
return ans ;
}
dfs(0 , n , digits , "" , phone , ans) ;
return ans ;
}
public void dfs(int x , int l , String digits , String str ,String[] phone , List<String> ans){
if(x == l){
ans.add(str) ;
return ;
}
int d= digits.charAt(x) - '0' ;
for(char c : phone[d].toCharArray()){
dfs(x+1 , l , digits , str+c , phone , ans ) ;
}
}
}