리트코드/midium
[리트코드] 17. Letter Combinations of a Phone Number - js (DFS)
bbeyak
2023. 8. 21. 12:37
반응형
1. 문제
https://leetcode.com/problems/letter-combinations-of-a-phone-number/
Letter Combinations of a Phone Number - LeetCode
Can you solve this real interview question? 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 d
leetcode.com
2. 코드
이 문제의 핵심은 순서가 있는 조합, 즉 순열이라는 것이다.
digits가 "23" 이라면 무조건 2 -> 3 순서대로 눌러진다. 3 -> 2 는 고려할 필요가 없다. 그래서 파라미터에 digits의 index가 들어간다. 매일 조합 문제만 풀다가 순열 문제를 오랜만에 푸니 조금 헷갈렸던 것 같다.
/**
* @param {string} digits
* @return {string[]}
*/
var letterCombinations = function(digits) {
if(!digits.length) return [];
const phone = {
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 combination = (str,idx) => {
if(str.length === digits.length){
answer.push(str);
}
else{
for(const letter of phone[digits[idx]]){
combination(str+letter,idx+1);
}
}
}
combination("",0);
return answer;
};
+ 오늘 오전에 코로나 확진 판정을 받았다.. 가족이 걸리니 어쩔 수 없이 나도 걸리게 되는 것 같다. 작년에 한 번 걸리고 비염 때문에 1년간 고생했는데.. 이제 좀 나아지나 싶더니 1년 3개월만에 또 걸렸다. 속상하다.

반응형