Given a string containing digits from
2-9
inclusive, 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. Note that 1 does not map to any letters.

Example:
Input: "23" Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
Note:
Although the above answer is in lexicographical order, your answer could be in any order you want.
For people looking for solution in Javascript, here is a recursive solution. for other languages, please convert the code
const group = [];
result = [];
let numstr = "";
var letterCombinations = function(num) {
numstr = num.toString();
const letters = [,,['a','b','c'],['d','e','f'],['g','h','i'],['j','k','l'],['m','n','o'],['p','q','r','s'],['t','u','v'],['w','x','y','z']];
for (let i=0; i<numstr.length; i++) {
group.push(letters[parseInt(numstr[i])]);
}
wordMaker(num, 0, "");
return result;
}
const wordMaker = (num, n, w) => {
for (let i=0; i<group[n].length; i++) {
if (n === group.length-1) {
result.push(w + group[n][i])
}
else {
wordMaker(num, n+1, w + group[n][i]);
}
}
}
Test Input
console.log(letterCombinations(23));
Output
[ 'ad', 'ae', 'af', 'bd', 'be', 'bf', 'cd', 'ce', 'cf' ]
Comments
Post a Comment