Letter Combinations of a Phone Number

Monisha Mathew
1 min readApr 11, 2019

--

Question: 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"].

You can view the full question here.

Approach 1: Let’s once again use recursion.

//Approach 1
//Runtime: 0ms
//Memory usage: 37MB
class Solution {
public List<String> letterCombinations(String digits) {
List<String> result = new ArrayList();
if(digits!=null && digits.length()>0)
getLetterComb(digits.toCharArray(), 0, "", result);
return result;
}

private void getLetterComb(char[] chars, int i, String curr, List<String> result){
char[] next = new char[]{};
switch(chars[i]){
case '2':
next = new char[]{'a','b','c'};
break;
case '3':
next = new char[]{'d','e','f'};
break;
case '4':
next = new char[]{'g','h','i'};
break;
case '5':
next = new char[]{'j','k','l'};
break;
case '6':
next = new char[]{'m','n','o'};
break;
case '7':
next = new char[]{'p','q','r','s'};
break;
case '8':
next = new char[]{'t','u','v'};
break;
case '9':
next = new char[]{'w','x','y','z'};
break;
}
for(char c : next){
String temp = curr+c;
if(i==chars.length-1){
result.add(temp);
} else {
getLetterComb(chars, i+1, temp, result);
}
}
}
}

Find more posts here.

Cheers & Chao!

--

--