Given a digit string excluded 01
, return all possible letter combinations that the number could represent.
A mapping of digit to letters just like on the telephone buttons
Example
Given "23"
Return ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]
public class Solution {
/**
* @param digits A digital string
* @return all posible letter combinations
*/
String[] map = new String[] {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs",
"tuv", "wxyz"};
public ArrayList<String> letterCombinations(String digits) {
if(digits.length() == 0) return new ArrayList<String>();;
ArrayList<String> res = new ArrayList<String>();
helper(digits, 0, "", res);
return res;
}
void helper(String digits, int pos, String str, ArrayList<String> list) {
if(pos == digits.length()) {
list.add(str);
return;
}
int s = digits.charAt(pos) - '0';
if(s == 0 || s == 1) {
helper(digits, pos + 1, str, list);
} else {
for(int j = 0; j < map[s].length(); j++) {
helper(digits, pos + 1, str + map[s].charAt(j), list);
}
}
}
}