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.
class Solution {
public void dfs(String digits, HashMap<Integer, String> map, List<String> lst,
StringBuilder s, int begin){
if ( begin == digits.length()){
lst.add(new String(s));
}
else {
String tmp = map.get(digits.charAt(begin) - '0');
for (int i = 0; i < tmp.length(); ++ i){
s.append(tmp.charAt(i));
dfs(digits, map, lst, s, begin + 1);
s.deleteCharAt(s.length() - 1);
}
}
}
public List<String> letterCombinations(String digits) {
HashMap<Integer, String> map = new HashMap<>();
map.put(0, "");
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");
List<String> lst = new ArrayList<>();
if (digits.length() == 0){
return lst;
}
StringBuilder s = new StringBuilder();
dfs(digits, map, lst, s, 0);
return lst;
}
}