Given a string containing digits from 2-9
inclusive, 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. Note that 1 does not map to any letters.
Example:
Input: "23" Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
Solution 1: DFS
When we need to find all possible solution or combinations or permutations, DFS can be used to solve this kind of problems. When do we put the string into result? String's length should be equal to digits' length. Otherwise, keep adding character. Also, these characters to be added next are those with corresponding number whose index in digits array are equal to current string's length. Note that StringBuilder cannot use remove(), use deleteCharAt() instead.
Code:
public List<String> letterCombinations(String digits) {
List<String> res = new ArrayList<>();
if (digits == null || digits.length() == 0){
return res;
}
String[] map = new String[]{"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
StringBuilder sb = new StringBuilder();
dfs(map, digits, res, sb);
return res;
}
private void dfs(String[] map, String digits, List<String> res, StringBuilder sb){
if (sb.length() == digits.length()){
res.add(new StringBuilder(sb).toString());
return;
}
int index = digits.charAt(sb.length()) - '0';
for (char c: map[index].toCharArray()){
sb.append(c);
dfs(map, digits, res, sb);
sb.deleteCharAt(sb.length() - 1);
}
}
Solution 2: BFS
We get first digit, store all characters corresponding to first digit as a current result list. Then get second digit and append each element in the current result list with every one of characters corresponding to second digit. When an element of current list is done with appending every one character of second digit, then remove the element and update current result list. Then get third digit and so on. We can use LinkedList since we need to append elements to current result list and remove element from head of current result list.
Code:
public List<String> letterCombinations(String digits) {
LinkedList<String> res = new LinkedList<>();
if (digits == null || digits.length() == 0){
return res;
}
String[] map = new String[]{"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
res.add("");
for (int i = 0; i < digits.length(); i++){
int index = digits.charAt(i) - '0';
while (res.peek().length() == i){
for (char c: map[index].toCharArray()){
res.add(res.peek() + c);
}
res.poll();
}
}
return res;
}