
은찬
var letterCombinations = function(digits) { const answer = []; const strings = ["", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"]; const length = digits.length; if(!digits.length){ return []; } const dfs = (current, index, size) => { const digit = parseInt(digits[index]); if(size === length - 1){ for(let i = 0; i < strings[digit].length; i++){ answer.push(current + strings[digit][i]); } return; } for(let i = 0; i < strings[digit].length; i++){ const string = current + strings[digit][i]; dfs(string, index + 1, size + 1); } } dfs("", 0, 0); return answer; };
재영
63 ms, faster than 83.91%
const letters = { 2: ['a', 'b', 'c'], 3: ['d', 'e', 'f'], 4: ['g', 'h', 'i'], 5: ['j', 'k', 'l'], 6: ['m', 'n', 'o'], 7: ['p', 'q', 'r', 's'], 8: ['t', 'u', 'v'], 9: ['w', 'x', 'y', 'z'], }; // digits -> 하나씩 앞에서 뺄 거에요. - 이게 지금 생각보다 시간 복잡도가 크지 않음. const letterCombinations = (digits, result = '', results = []) => { if (!digits.length) { // NOTE: 예외 처리. if (result === '') return []; results.push(result); return results; } const now = digits[0]; digits = digits.slice(1); const nowLetters = letters[now]; for (let i = 0; i < nowLetters.length; i += 1) { const nextResult = result + nowLetters[i]; results = letterCombinations(digits, nextResult, results); } return results; }; (() => { const digits = '23'; console.log(letterCombinations(digits)); })(); (() => { const digits = ''; console.log(letterCombinations(digits)); })();
const recursiveFunc = (condition, string, result = []) => { // 1. 백트래킹부터 먼저 생각 // 2. 백트래킹의 리턴되는 순간을 생각하고 // 3. 리턴되기 위한 조건을 생각한다. // 4. 조건을 만족했을 때 반환되는 값을 업데이트하는 로직을 생각한다. // 5. 현재 주어진 값으로는 못할 경우에 커스터마이징 if (!condition.length) { result.push(string) return result; } ... }
효성
//풀다 포기한 풀이;_; var letterCombinations = function(digits) { const splited = digits.split(''); const letter = { 2 : ['a', 'b', 'c'], 3 : ['d', 'e', 'f'], 4 : ['g', 'h', 'i'], 5 : ['j', 'k', 'l'], 6 : ['m', 'n', 'o'], 7 : ['p', 'q', 'r', 's'], 8 : ['t', 'u', 'v'], 9 : ['w', 'x', 'y', 'z'] } const getCombination = (arr, selectNumber) => { const result = []; if(selectNumber === 1) return arr.map(el => [el]); arr.forEach((fixed, i, origin) => { const rest = origin.slice(i + 1); const combination = getCombination(rest, selectNumber -1); const attached = combination.map(el => [fixed, ...el]); result.push(...attached); }); return result; } const arr = splited.map(digit => letter[digit]); console.log(getCombination(arr, splited.length)) };
//참고한 풀이 const letterCombinations = (digits) => { if (digits == null || digits.length === 0) return []; const map = { 2: 'abc', 3: 'def', 4: 'ghi', 5: 'jkl', 6: 'mno', 7: 'pqrs', 8: 'tuv', 9: 'wxyz', }; const res = []; const go = (i, s) => { if (i === digits.length) { res.push(s); return; } for (const c of map[digits[i]]) { go(i + 1, s + c); } }; go(0, ''); return res; };