Letter Combinations of a Phone Number
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. Note that 1 does not map to any letters.
Input: digits = "23"
Output: ["ad","ae","af","bd","be","bf","cd","ce","cf"]
const letterCombinations = function (digits) { if (!digits) return [] const map = { 2: 'abc', 3: 'def', 4: 'ghi', 5: 'jkl', 6: 'mno', 7: 'pqrs', 8: 'tuv', 9: 'wxyz', } // We add all 3 or 4 characters of a given digit // to the "so-far" calculated result, one by one. // // Consider the so-far result as ["a", "b", "c"]. // The given digit is 4, so its characters are: "g", "h", "i" // So we add each character to each element of the result. // ["ag", "bg", "cg"] let ans = [''] for (let i = 0; i < digits.length; i++) { const temp = [] const curDigit = digits[i] const letters = map[curDigit] for (const l of letters) { for (const a of ans) { temp.push(a + l) } } ans = temp } return ans }
const letterCombinations = function (digits) { if (!digits) return [] const map = { 2: 'abc', 3: 'def', 4: 'ghi', 5: 'jkl', 6: 'mno', 7: 'pqrs', 8: 'tuv', 9: 'wxyz', } // For a given digits: 23, the pressed will look like this // ["abc", "def"] // Now, go like this: // a -> def // ad, ae, af // b -> def // bd, be, bf // c -> def // cd, ce, cf const pressed = [] for (const d of digits) { pressed.push(map[d]) } let ans = [] function iterator(start, str) { if (start >= pressed.length) { ans.push(str) return } const curStr = pressed[start] for (let idx = 0; idx < curStr.length; idx++) { const curChar = curStr[idx] iterator(start + 1, str + curChar) } } iterator(0, '') return ans }