Time complexity : O(3^N × 4^M ) where N is the number of digits in the input that maps to 3 letters (e.g. 2, 3, 4, 5, 6, 8) and M is the number of digits in the input that maps to 4 letters (e.g. 7, 9), and N+M is the total number digits in the input.
Space complexity : O(3^N × 4^M ) since one has to keep 3^N times 4^M solutions.
class Solution {
private static final String[] KEYS = { "", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };
public List<String> letterCombinations(String digits) {
List<String> res = new ArrayList<>();
if (digits.length() == 0) {
return res;
}
helper(digits, 0, "", res);
return res;
}
private void helper(String digits, int index, String path, List<String> res) {
if (index == digits.length()) {
res.add(path.toString());
return;
}
String letters = KEYS[digits.charAt(index) - '0'];
for (char c : letters.toCharArray()) {
helper(digits, index + 1, path + c, res);
}
}
}
Queue, BFS
class Solution {
public List<String> letterCombinations(String digits) {
LinkedList<String> queue = new LinkedList();
if (digits == null || digits.length() == 0) {
return queue;
}
char[] digitChar = digits.toCharArray();
String[] phone = new String[] {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
queue.offer("");
for (int i = 0; i < digitChar.length; i++) {
char[] letters = phone[digitChar[i] - '0'].toCharArray();
while (queue.peek().length() == i) {
String str = queue.poll();
for (char c : letters) {
queue.offer(str + c);
}
}
}
return queue;
}
}