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.
Use a hashmap to store the digits and corresponding strings. Similar to subsets, permutations, use recursion with iteration to find all possible results.
public class Solution {
public ArrayList<String> letterCombinations(String digits) {
ArrayList<String> res = new ArrayList<String>();
if (digits == null) {
return res;
}
HashMap<Character, String> map = new HashMap<Character, String>();
map.put('1', "");
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");
map.put('0', " ");
StringBuilder item = new StringBuilder();
helperPhone(digits, map, res, item, 0);
return res;
}
private void helperPhone(String digits, HashMap<Character, String> map,
ArrayList<String> res, StringBuilder item, int pos) {
if (pos == digits.length()) {
res.add(item.toString());
return;
}
String number = map.get(digits.charAt(pos));
for (int j = 0; j < number.length(); j++) {
item.append(number.charAt(j));
helperPhone(digits, map, res, item, pos + 1);
item.deleteCharAt(item.length() - 1);
}
}
}