|
| 1 | +--- |
| 2 | +id: Letter Combinations of a Phone Number |
| 3 | +title: Letter Combinations of a Phone Number (LeetCode) |
| 4 | +sidebar_label: 0017-Letter-Combinations-of-a-Phone-Number |
| 5 | +tags: |
| 6 | + - Back Tracking |
| 7 | + - Mapping |
| 8 | + - String |
| 9 | +description: The problem requires generating all letter combinations corresponding to given digits (2-9). The solution utilizes backtracking to explore all combinations efficiently, employing a recursive approach in Java. |
| 10 | +--- |
| 11 | + |
| 12 | +## Problem Description |
| 13 | + |
| 14 | +| Problem Statement | Solution Link | LeetCode Profile | |
| 15 | +| :----------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------ | :------------------------------------------------- | |
| 16 | +| [Letter Combinations of a Phone Number](https://leetcode.com/problems/Letter Combinations of a Phone Number/) | [Letter Combinations of a Phone Number Solution on LeetCode](https://leetcode.com/problems/Letter Combinations of a Phone Number/solutions/5055810/video-two-pointer-solution/) | [gabaniyash846](https://leetcode.com/u/gabaniyash846/) | |
| 17 | + |
| 18 | +### Problem Description |
| 19 | + |
| 20 | +## Problem Statement: |
| 21 | +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. |
| 22 | + |
| 23 | +### Examples |
| 24 | + |
| 25 | +#### Example 1 |
| 26 | + |
| 27 | +- **Input:** `digits = "23"` |
| 28 | +- **Output:** `["ad","ae","af","bd","be","bf","cd","ce","cf"]` |
| 29 | + |
| 30 | +#### Example 2 |
| 31 | + |
| 32 | +- **Input:** `digits = ""` |
| 33 | +- **Output:** `[]` |
| 34 | + |
| 35 | + |
| 36 | +#### Example 3 |
| 37 | + |
| 38 | +- **Input:** `2` |
| 39 | +- **Output:** `["a","b","c"]` |
| 40 | + |
| 41 | +### Constraints: |
| 42 | +- `0 ≤ digits.length ≤ 4` |
| 43 | +- `0 ≤ digits.length ≤ 4digits[𝑖]` |
| 44 | +- `digits[i] is a digit in the range ['2', '9'].` |
| 45 | +- `A mapping of digits to letters (similar to telephone buttons) is given below. Note that 1 does not map to any letters.` |
| 46 | + |
| 47 | +### Approach |
| 48 | + |
| 49 | +1. **Mapping Digits to Letters:** |
| 50 | + - Define a mapping of digits to their corresponding letters, similar to telephone buttons. |
| 51 | + |
| 52 | +2. **Backtracking Function:** |
| 53 | + - Define a recursive backtracking function to generate all possible combinations. |
| 54 | + - The function takes four parameters: |
| 55 | + - `index`: The current index in the digits string. |
| 56 | + - `path`: The current combination of letters. |
| 57 | + - If the index is equal to the length of the digits string, it means we have reached the end of a combination, so we add it to the result list. |
| 58 | + - Otherwise, for each letter corresponding to the current digit, we append it to the current combination and recursively call the function with the next index. |
| 59 | + - After the recursive call, we remove the last character from the combination (backtracking). |
| 60 | + |
| 61 | +3. **Base Case:** |
| 62 | + - If the length of the current combination is equal to the length of the input digits string, we add the combination to the result list. |
| 63 | + |
| 64 | +4. **Main Function:** |
| 65 | + - Initialize an empty list to store the combinations. |
| 66 | + - Call the backtracking function with the initial index set to 0 and an empty string as the initial combination. |
| 67 | + - Return the list of combinations. |
| 68 | + |
| 69 | +This approach ensures that all possible combinations are generated using backtracking, and the result is returned in the desired format. |
| 70 | + |
| 71 | +### Solution Code |
| 72 | + |
| 73 | +#### Python |
| 74 | + |
| 75 | +```python |
| 76 | +class Solution: |
| 77 | + def letterCombinations(self, digits: str) -> List[str]: |
| 78 | + if not digits: |
| 79 | + return [] |
| 80 | + |
| 81 | + digit_to_letters = { |
| 82 | + '2': 'abc', |
| 83 | + '3': 'def', |
| 84 | + '4': 'ghi', |
| 85 | + '5': 'jkl', |
| 86 | + '6': 'mno', |
| 87 | + '7': 'pqrs', |
| 88 | + '8': 'tuv', |
| 89 | + '9': 'wxyz' |
| 90 | + } |
| 91 | + |
| 92 | + def backtrack(index, path): |
| 93 | + if index == len(digits): |
| 94 | + combinations.append(path) |
| 95 | + return |
| 96 | + for letter in digit_to_letters[digits[index]]: |
| 97 | + backtrack(index + 1, path + letter) |
| 98 | + |
| 99 | + combinations = [] |
| 100 | + backtrack(0, '') |
| 101 | + return combinations |
| 102 | +``` |
| 103 | + |
| 104 | +#### Java |
| 105 | + |
| 106 | +```java |
| 107 | +import java.util.ArrayList; |
| 108 | +import java.util.HashMap; |
| 109 | +import java.util.List; |
| 110 | +import java.util.Map; |
| 111 | + |
| 112 | +public class Solution { |
| 113 | + private Map<Character, String> digitToLetters = new HashMap<>(); |
| 114 | + |
| 115 | + public Solution() { |
| 116 | + digitToLetters.put('2', "abc"); |
| 117 | + digitToLetters.put('3', "def"); |
| 118 | + digitToLetters.put('4', "ghi"); |
| 119 | + digitToLetters.put('5', "jkl"); |
| 120 | + digitToLetters.put('6', "mno"); |
| 121 | + digitToLetters.put('7', "pqrs"); |
| 122 | + digitToLetters.put('8', "tuv"); |
| 123 | + digitToLetters.put('9', "wxyz"); |
| 124 | + } |
| 125 | + |
| 126 | + public List<String> letterCombinations(String digits) { |
| 127 | + List<String> combinations = new ArrayList<>(); |
| 128 | + if (digits == null || digits.isEmpty()) { |
| 129 | + return combinations; |
| 130 | + } |
| 131 | + backtrack(combinations, digits, 0, new StringBuilder()); |
| 132 | + return combinations; |
| 133 | + } |
| 134 | + |
| 135 | + private void backtrack(List<String> combinations, String digits, int index, StringBuilder path) { |
| 136 | + if (index == digits.length()) { |
| 137 | + combinations.add(path.toString()); |
| 138 | + return; |
| 139 | + } |
| 140 | + String letters = digitToLetters.get(digits.charAt(index)); |
| 141 | + for (char letter : letters.toCharArray()) { |
| 142 | + path.append(letter); |
| 143 | + backtrack(combinations, digits, index + 1, path); |
| 144 | + path.deleteCharAt(path.length() - 1); |
| 145 | + } |
| 146 | + } |
| 147 | + |
| 148 | + public static void main(String[] args) { |
| 149 | + Solution solution = new Solution(); |
| 150 | + List<String> result = solution.letterCombinations("23"); |
| 151 | + System.out.println(result); // Output: [ad, ae, af, bd, be, bf, cd, ce, cf] |
| 152 | + } |
| 153 | +} |
| 154 | +``` |
| 155 | + |
| 156 | +#### CPP: |
| 157 | +```cpp |
| 158 | +#include <iostream> |
| 159 | +#include <vector> |
| 160 | +#include <unordered_map> |
| 161 | + |
| 162 | +using namespace std; |
| 163 | + |
| 164 | +class Solution { |
| 165 | +private: |
| 166 | + unordered_map<char, string> digitToLetters; |
| 167 | + vector<string> combinations; |
| 168 | + |
| 169 | +public: |
| 170 | + Solution() { |
| 171 | + digitToLetters = { |
| 172 | + {'2', "abc"}, |
| 173 | + {'3', "def"}, |
| 174 | + {'4', "ghi"}, |
| 175 | + {'5', "jkl"}, |
| 176 | + {'6', "mno"}, |
| 177 | + {'7', "pqrs"}, |
| 178 | + {'8', "tuv"}, |
| 179 | + {'9', "wxyz"} |
| 180 | + }; |
| 181 | + } |
| 182 | + |
| 183 | + vector<string> letterCombinations(string digits) { |
| 184 | + if (digits.empty()) return {}; |
| 185 | + backtrack(digits, 0, ""); |
| 186 | + return combinations; |
| 187 | + } |
| 188 | + |
| 189 | + void backtrack(const string& digits, int index, string path) { |
| 190 | + if (index == digits.length()) { |
| 191 | + combinations.push_back(path); |
| 192 | + return; |
| 193 | + } |
| 194 | + for (char letter : digitToLetters[digits[index]]) { |
| 195 | + backtrack(digits, index + 1, path + letter); |
| 196 | + } |
| 197 | + } |
| 198 | +}; |
| 199 | + |
| 200 | +int main() { |
| 201 | + Solution solution; |
| 202 | + vector<string> result = solution.letterCombinations("23"); |
| 203 | + for (const string& comb : result) { |
| 204 | + cout << comb << " "; |
| 205 | + } |
| 206 | + // Output: ad ae af bd be bf cd ce cf |
| 207 | + return 0; |
| 208 | +} |
| 209 | +``` |
| 210 | +
|
| 211 | +#### JavaScript |
| 212 | +```js |
| 213 | +/** |
| 214 | + * @param {string} digits |
| 215 | + * @return {string[]} |
| 216 | + */ |
| 217 | +var letterCombinations = function(digits) { |
| 218 | + if (digits.length === 0) return []; |
| 219 | + |
| 220 | + const digitToLetters = { |
| 221 | + '2': 'abc', |
| 222 | + '3': 'def', |
| 223 | + '4': 'ghi', |
| 224 | + '5': 'jkl', |
| 225 | + '6': 'mno', |
| 226 | + '7': 'pqrs', |
| 227 | + '8': 'tuv', |
| 228 | + '9': 'wxyz' |
| 229 | + }; |
| 230 | + |
| 231 | + const combinations = []; |
| 232 | + |
| 233 | + const backtrack = (index, path) => { |
| 234 | + if (index === digits.length) { |
| 235 | + combinations.push(path); |
| 236 | + return; |
| 237 | + } |
| 238 | + const letters = digitToLetters[digits.charAt(index)]; |
| 239 | + for (let letter of letters) { |
| 240 | + backtrack(index + 1, path + letter); |
| 241 | + } |
| 242 | + }; |
| 243 | + |
| 244 | + backtrack(0, ''); |
| 245 | + return combinations; |
| 246 | +}; |
| 247 | +
|
| 248 | +// Example usage: |
| 249 | +console.log(letterCombinations("23")); // Output: ["ad","ae","af","bd","be","bf","cd","ce","cf"] |
| 250 | +``` |
| 251 | + |
| 252 | +#### TypeScript |
| 253 | +```ts |
| 254 | +class Solution { |
| 255 | + private digitToLetters: { [key: string]: string } = { |
| 256 | + '2': 'abc', |
| 257 | + '3': 'def', |
| 258 | + '4': 'ghi', |
| 259 | + '5': 'jkl', |
| 260 | + '6': 'mno', |
| 261 | + '7': 'pqrs', |
| 262 | + '8': 'tuv', |
| 263 | + '9': 'wxyz' |
| 264 | + }; |
| 265 | + |
| 266 | + letterCombinations(digits: string): string[] { |
| 267 | + const combinations: string[] = []; |
| 268 | + |
| 269 | + const backtrack = (index: number, path: string): void => { |
| 270 | + if (index === digits.length) { |
| 271 | + combinations.push(path); |
| 272 | + return; |
| 273 | + } |
| 274 | + const letters = this.digitToLetters[digits.charAt(index)]; |
| 275 | + for (let letter of letters) { |
| 276 | + backtrack(index + 1, path + letter); |
| 277 | + } |
| 278 | + }; |
| 279 | + |
| 280 | + if (digits.length !== 0) { |
| 281 | + backtrack(0, ''); |
| 282 | + } |
| 283 | + |
| 284 | + return combinations; |
| 285 | + } |
| 286 | +} |
| 287 | + |
| 288 | +// Example usage: |
| 289 | +const solution = new Solution(); |
| 290 | +console.log(solution.letterCombinations("23")); // Output: ["ad","ae","af","bd","be","bf","cd","ce","cf"] |
| 291 | +``` |
| 292 | + |
| 293 | +### Step-by-Step Algorithm |
| 294 | + |
| 295 | +Here's a step-by-step algorithm for generating all possible letter combinations of a given string of digits using backtracking: |
| 296 | + |
| 297 | +1. **Define a mapping of digits to letters:** |
| 298 | + - Create a map where each digit from 2 to 9 is mapped to its corresponding letters on a telephone keypad. |
| 299 | + |
| 300 | +2. **Define a backtracking function:** |
| 301 | + - The function will take the following parameters: |
| 302 | + - `index`: The current index in the digits string. |
| 303 | + - `path`: The current combination of letters. |
| 304 | + - If the index is equal to the length of the digits string, it means we have formed a complete combination, so add it to the result list. |
| 305 | + - Otherwise, for each letter corresponding to the current digit at the given index, append it to the current combination and recursively call the function with the next index. |
| 306 | + - After the recursive call, remove the last character from the combination (backtracking). |
| 307 | + |
| 308 | +3. **Base Case:** |
| 309 | + - If the length of the current combination is equal to the length of the input digits string, add the combination to the result list. |
| 310 | + |
| 311 | +4. **Main Function:** |
| 312 | + - Initialize an empty list to store the combinations. |
| 313 | + - Call the backtracking function with the initial index set to 0 and an empty string as the initial combination. |
| 314 | + - Return the list of combinations. |
| 315 | + |
| 316 | +This algorithm ensures that all possible combinations are generated by exploring all valid paths through backtracking. |
0 commit comments