LeetCode Q 17 - Letter Combinations of a Phone Number
Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent.
Example:Input: "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.
Solution : Backtracking
Code:
private static final String[] KEYS = { "", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };
private List<String> res;
public List<String> letterCombinations(String digits) {
res = new ArrayList<>();
if (digits == null || digits.length() == 0) return res;
backtrack(digits, 0, "");
return res;
}
private void backtrack(String digits, int pos, String curr) {
// corner cases
if (pos == digits.length()) {
res.add(curr); return;
}
String letters = KEYS[digits.charAt(pos) - '0'];
for (char letter: letters.toCharArray())
backtrack(digits, pos + 1, curr + letter);
}