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.
public class Solution {
public List<String> letterCombinations(String digits) {
String[] map = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
List<String> res = new ArrayList<String>();
rec(res, new StringBuilder(), digits, map, 0);
return res;
}
private void rec(List<String> res, StringBuilder sb, String digits, String[] map, int level){
if(level==digits.length() ){
res.add(sb.toString());
return;
}
String s = map[digits.charAt(level)-'2'];
for(int i=0; i<s.length(); i++) {
sb.append(s.charAt(i));
rec(res, sb, digits, map, level+1);
sb.deleteCharAt(sb.length()-1);
}
}
}
本文介绍了一个算法问题:给定一个数字字符串,返回所有可能的字母组合。文章提供了一个Java实现方案,通过递归方法生成所有可能的组合。

238

被折叠的 条评论
为什么被折叠?



