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 ArrayList<String> letterCombinations(String digits) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
ArrayList<String> res = new ArrayList<String>();
get_comb(res, digits, new StringBuilder(""), 0);
return res;
}
public void get_comb(ArrayList<String> res, String digits, StringBuilder s, int pos){
String[] letters = {"0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
if(pos == digits.length()){
res.add(s.toString());
return;
}
int num = digits.charAt(pos) - '0';
for(int i = 0; i < letters[num].length(); i++){
s.append(letters[num].charAt(i));
get_comb(res, digits, s, pos + 1);
s.deleteCharAt(s.length() - 1);
}
}
}
本文介绍了一种基于电话按键映射的数字转字母组合算法,通过递归调用实现字符串到对应字母的转换,输出所有可能的组合。
553

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



