[JS] Letter Combinations of a Phone Number
2022. 9. 1. 17:43
🔒 문제 (LeetCode 17)
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.
Constraints:
- 0 <= digits.length <= 4
- digits[i] is a digit in the range ['2', '9'].
🌊 입출력
Example 1:
Input: digits = "23"
Output: ["ad","ae","af","bd","be","bf","cd","ce","cf"]
Example 2:
Input: digits = ""
Output: []
Example 3:
Input: digits = "2"
Output: ["a","b","c"]
🔑 해결
🌌 알고리즘 - DFS
/**
* @param {string} digits
* @return {string[]}
*/
var letterCombinations = function(digits) {
if(digits === null || digits.length === 0) return []
const buttons = ['', '', 'abc', 'def', 'ghi', 'jkl', 'mno', 'pqrs', 'tuv', 'wxyz']
const result = []
const dfs = (str, idx) => {
if(idx === digits.length) {
result.push(str)
return
}
for(const letter of buttons[digits[idx]]) {
dfs(str + letter, idx + 1)
}
}
dfs('', 0)
return result
};
'코딩테스트 (JS) > DFS | BFS' 카테고리의 다른 글
[JS] Word Search (0) | 2022.09.02 |
---|---|
[JS] Generate Parentheses (0) | 2022.09.01 |
[JS] Combination Sum II (0) | 2022.08.31 |
[JS] Combination Sum (0) | 2022.08.31 |
[JS] Permutations II (0) | 2022.08.31 |