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.
解释:0,1,2,3,4,5,6,7,8,9 这几个数字分别对应 {"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"}字母,给定一串数字,求解出所有可能的字母组合。
思路:既然是穷举出所有可能,当然深度优先遍历最容易理解。当长度满足要求时,保存即可。每种数字对应的字母个数不同,当然要每个对应字母都要考虑到。
public static final String[] lex = {"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
public List<String> letterCombinations(String digits) {
List<String> l = new ArrayList();
if(digits.length()==0) return l;
dfs(0,digits,"",l);
return l;
}
public static void dfs(int index,String digits,String prefix,List list){
if(index>=digits.length()){
list.add(prefix);
return;
}
for(int i = 0;i<lex[digits.charAt(index)-'0'].length();i++){
dfs(index+1,digits,prefix+lex[digits.charAt(index)-'0'].charAt(i),list);
}
}