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”].

Recursive solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class Solution {
private static final String[] KEYS = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
public List<String> letterCombinations(String digits) {
List<String> result = new LinkedList<String>();
if (digits == null || digits.length() == 0) return result;
combine(result, new StringBuilder(), digits, 0);
return result;
}

public void combine(List<String> result, StringBuilder sb, String digits, int index) {
if (sb.length() >= digits.length()) {
result.add(sb.toString());
} else {
String letters = KEYS[digits.charAt(index) - '0'];
for (int i = 0; i < letters.length(); i++) {
sb.append(letters.charAt(i));
combine(result, sb, digits, index + 1);
sb.setLength(sb.length() - 1);
}
}
}
}

Iterative solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class Solution {
public List<String> letterCombinations(String digits) {
LinkedList<String> ans = new LinkedList<String>();
if (digits == null || digits.length() == 0) {
return ans;
}
String[] mapping = new String[] {"0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
ans.add("");
for(int i =0; i<digits.length();i++){
int x = Character.getNumericValue(digits.charAt(i));
while(ans.peek().length()==i){
String t = ans.remove();
for(char s : mapping[x].toCharArray())
ans.add(t+s);
}
}
return ans;
}
}