|
| 1 | +functionletterCombinations(digits){ |
| 2 | +// If the input is an empty string, return an empty array. |
| 3 | +if(digits.length===0){ |
| 4 | +return[]; |
| 5 | +} |
| 6 | + |
| 7 | +// Mapping of digits to letters as per the telephone keypad using a javascript dictionary. |
| 8 | +constdigitToChar={ |
| 9 | +'2':['a','b','c'], |
| 10 | +'3':['d','e','f'], |
| 11 | +'4':['g','h','i'], |
| 12 | +'5':['j','k','l'], |
| 13 | +'6':['m','n','o'], |
| 14 | +'7':['p','q','r','s'], |
| 15 | +'8':['t','u','v'], |
| 16 | +'9':['w','x','y','z'] |
| 17 | +}; |
| 18 | + |
| 19 | +// Resultant array to store all possible combinations |
| 20 | +constresult=[]; |
| 21 | + |
| 22 | +// Backtracking function to generate combinations |
| 23 | +functionbacktrack(index,currentCombination){ |
| 24 | +// if the current combination has the same length as the input digits. |
| 25 | +if(index===digits.length){ |
| 26 | +result.push(currentCombination); |
| 27 | +return; |
| 28 | +} |
| 29 | + |
| 30 | +// Get the letters that the current digit maps to. |
| 31 | +letletters=digitToChar[digits[index]]; |
| 32 | + |
| 33 | +// Loop through the letters and call backtrack recursively for the next digit. |
| 34 | +for(letletterofletters){ |
| 35 | +backtrack(index+1,currentCombination+letter); |
| 36 | +} |
| 37 | +} |
| 38 | + |
| 39 | +// Start backtracking from the first digit (index 0) with an empty string as the initial combination. |
| 40 | +backtrack(0,''); |
| 41 | + |
| 42 | +returnresult; |
| 43 | +}; |