A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.
Copy Input: digits = "23"
Output: ["ad","ae","af","bd","be","bf","cd","ce","cf"]
Copy Input: digits = ""
Output: []
Copy Input: digits = "2"
Output: ["a","b","c"]
Copy class Solution {
private Map<Integer, String> charMap;
private List<String> res;
public List<String> letterCombinations(String digits) {
res = new ArrayList<>();
if(digits == null || digits.length() == 0)
{
return res;
}
charMap = buildMap();
StringBuilder sb = new StringBuilder();
dfs(digits, 0, sb);
return res;
}
public Map<Integer, String> buildMap()
{
Map<Integer, String> res = new HashMap<>();
res.put(2, "abc");
res.put(3, "def");
res.put(4, "ghi");
res.put(5, "jkl");
res.put(6, "mno");
res.put(7, "pqrs");
res.put(8, "tuv");
res.put(9, "wxyz");
return res;
}
public void dfs(String digits, int start, StringBuilder sb)
{
if (start == digits.length())
{
res.add(sb.toString());
return;
}
String currentChar = charMap.get(digits.charAt(start) - '0');
for(char c : currentChar.toCharArray())
{
sb.append(c);
dfs(digits, start+1, sb);
sb.deleteCharAt(sb.length()-1);
}
}
}