- 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.
A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.
Solution 1
Time Complexity: O(3N*4M), where N is the number of digits whose corresponding letters has 3 length and M is the number of digits whose corresponding letters has 4 length. space Complexity: O(3N*4M)
class Solution {
Map<String, String> symbol = new HashMap<String, String>(){{
put("2", "abc");
put("3", "def");
put("4", "ghi");
put("5", "jkl");
put("6", "mno");
put("7", "pqrs");
put("8", "tuv");
put("9", "wxyz");
}};
List<String> output = new ArrayList<String>();
public List<String> letterCombinations(String digits) {
if(digits.length() > 0)
getLetters("",digits);
return output;
}
private void getLetters(String combination, String digits) {
// if reach the end of digits, add combination to output
if(digits.length()== 0){
output.add(combination);
} else {
//for each letter, find add it to combination and continue the next digits
String letters = symbol.get(digits.substring(0,1));
for(int i = 0; i < letters.length(); i++) {
getLetters(combination+letters.substring(i,i+1), digits.substring(1));
}
}
}
}