[Leetcode] 17. Letter Combinations of a Phone Number β
Problem β
μ£Όμ΄μ§ μ«μ λ€μ΄μΌμ μ΄μ©νμ¬ μλ ν€ν¨λλ‘ λμ¬μ μλ λ¬Έμ μ‘°ν©μ λͺ¨λ ꡬνμ¬νλ €.
Solution β
- λ²νΈλ§λ€ ν€ λ°°μ΄μ λ§€νν΄λλ€.
- μ¬κ·ν¨μλ₯Ό μ΄μ©ν΄μ μμ°¨μ μΌλ‘ μ¬μμλ κ²½μ°μλν΄ μ΅λ κΈΈμ΄μμ κ°μ μ μ₯ν΄λλ€.
JS CODE β
javascript
/**
* @param {string} digits
* @return {string[]}
*/
var letterCombinations = function (digits) {
const phoneKeypad = {
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'],
}
let answer = []
const combinationStr = (digits, deep, strs) => {
if (deep === digits.length) {
strs.join() && answer.push(strs.join(''))
return
}
for (const d of phoneKeypad[digits[deep]]) {
strs[deep] = d
combinationStr(digits, deep + 1, strs)
}
}
combinationStr(digits, 0, Array(digits.length))
return answer
}