Given a string containing digits from 2-9
inclusive, 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. Note that 1 does not map to any letters.
Example:
Input: "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
题目要求
- 给定数字字符序列,求出所有可能的字符的组合
解题思路
采用递归法解,先求出n-1个数字字符的结果,然后枚举该结果与第n个数字字符对应的字母,在将结果加入到result中。注意边界条件的处理
超过100%的java提交
class Solution {
private String[] letter={
"abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"
};
public List<String> letterCombinations(String digits) {
List<String> result = new ArrayList<String>();
recursive(digits,result);
return result;
}
private void recursive(String digits,List<String> result){
if(digits.length()==0) return;
if(digits.length()==1) {
int num = digits.charAt(0)-'0'-2;
for(int i = 0;i < letter[num].length();i++){
char c0 = letter[num].charAt(i);
result.add((new StringBuffer().append(c0)).toString());
}
return ;
}
String str = digits.substring(0,digits.length()-1);
recursive(str,result);
char c = digits.charAt(digits.length()-1);
int num = c-'0'-2;
List<String> list = new ArrayList<>();
for(int j = 0;j < result.size();j++){
String it = result.get(j);
for(int i = 0;i < letter[num].length();i++){
list.add(it+letter[num].charAt(i));
}
}
result.clear();
result.addAll(list);
}
}