题目
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"].
答案
class Solution {
public List<String> letterCombinations(String digits) {
List<String> list = new ArrayList<String>();
HashMap<Character, String> map = new HashMap<Character, String>();
map.put('2', "abc");
map.put('3', "def");
map.put('4', "ghi");
map.put('5', "jkl");
map.put('6', "mno");
map.put('7', "pqrs");
map.put('8', "tuv");
map.put('9', "wxyz");
recur(digits, 0, "", list, map);
return list;
}
public void recur(String digits, int curr_index, String curr_letters, List<String> list, HashMap<Character, String> map) {
if(curr_index == digits.length()) {
if(!curr_letters.equals(""))
list.add(curr_letters);
return;
}
char digit = digits.charAt(curr_index);
if(digit == '0' || digit == '1') {
recur(digits, curr_index + 1, curr_letters, list, map);
return;
}
// Three choices
String s = map.get(digit);
for(int i = 0; i < s.length(); i++) {
recur(digits, curr_index + 1, curr_letters + s.charAt(i), list, map);
}
}
}