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"].
class Solution {
public List<String> letterCombinations(String digits) {
List<String> res = new ArrayList<>();
if (digits == null || digits.length() == 0) {
return res;
}
String[] keys = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
StringBuilder combination = new StringBuilder();
getLetterCombinations(digits, 0, combination, keys, res);
return res;
}
public void getLetterCombinations(String digits, int pos, StringBuilder combination, String[] keys, List<String> res) {
if (pos == digits.length()) {
res.add(combination.toString());
return;
}
String key = keys[digits.charAt(pos) - '0'];
for (int i = 0; i < key.length(); i++) {
combination.append(key.charAt(i));
getLetterCombinations(digits, pos + 1, combination, keys, res);
combination.setLength(combination.length() - 1);
}
}
}
3. Time & Space Complexity