Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. Return the answer in any order.
A mapping of digits to letters (just like on the telephone buttons) is given below:
Input: digits = "23"
Output: ["ad","ae","af","bd","be","bf","cd","ce","cf"]
Input: digits = ""
Output: []
Input: digits = "2"
Output: ["a","b","c"]
Classic Cartesian Product: For each digit, choose one of its letters.
For "23":
Backtracking approach: Build combinations character by character.
This is a Backtracking with Mapping problem:
phone = {
'2': 'abc', '3': 'def', '4': 'ghi',
'5': 'jkl', '6': 'mno', '7': 'pqrs',
'8': 'tuv', '9': 'wxyz'
}
def backtrack(index, current):
if index == len(digits):
result.append(current)
return
for letter in phone[digits[index]]:
backtrack(index + 1, current + letter)
Time: O(4^n × n) where n = digits length
Space: O(n) recursion depth
1import java.util.*;
2
3class Solution {
4 private static final String[] PHONE = {
5 "", // 0
6 "", // 1
7 "abc", // 2
8 "def", // 3
9 "ghi", // 4
10 "jkl", // 5
11 "mno", // 6
12 "pqrs", // 7
13 "tuv", // 8
14 "wxyz" // 9
15 };
16
17 public List<String> letterCombinations(String digits) {
18 List<String> result = new ArrayList<>();
19 if (digits == null || digits.length() == 0) {
20 return result;
21 }
22
23 backtrack(digits, 0, new StringBuilder(), result);
24 return result;
25 }
26
27 private void backtrack(String digits, int index, StringBuilder current, List<String> result) {
28 if (index == digits.length()) {
29 result.add(current.toString());
30 return;
31 }
32
33 String letters = PHONE[digits.charAt(index) - '0'];
34 for (char letter : letters.toCharArray()) {
35 current.append(letter);
36 backtrack(digits, index + 1, current, result);
37 current.deleteCharAt(current.length() - 1);
38 }
39 }
40}
41