题目描述:
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.
解题思路:
递归法解题之。从第一个字符串开始确认结果,然后递归地确认余下各项结果。
参考博客:http://blog.csdn.net/china_wanglong/article/details/38495355
代码如下:
public class Solution {
public List<String> letterCombinations(String digits) {
List<String> result = new ArrayList<String>();
String[] map = new String[] { "", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };
char[] tmp = new char[digits.length()];
if(digits.length() == 0)
return result;
rec(digits, 0, tmp, map, result);
return result;
}
public void rec(String digits, int index, char[] tmp, String[] map, List<String> result){
if(index == digits.length()){
result.add(new String(tmp));
return;
}
char tmpChar = digits.charAt(index);
for(int i = 0; i < map[tmpChar - '0'].length(); i++){
tmp[index] = map[tmpChar - '0'].charAt(i);
rec(digits, index + 1, tmp, map, result);
}
}
}