728x90
telephoneword 문제
recursion 활용한 또 다른 문제
이것도 가위바위보 문제의 변형으로 생각하고 풀면 될듯하다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 | /* * Each number key on a standard phone keypad has a set of Latin letters written on * it as well: http://en.wikipedia.org/wiki/File:Telephone-keypad2.svg * * Businesses often try to come up with clever ways to spell out their phone number * in advertisements to make it more memorable. But there are a lot of combinations! * * Write a function that takes up to four digits of a phone number, and * returns a list of all of the words that can be written on the phone with * that number. (You should return all permutations, not only English words.) * * Example: * telephoneWords('2745'); * => ['APGJ', * 'APGK', * 'APGL', * ..., // many many more of these * 'CSIL'] * * Tips: * - Phone numbers are strings! (A phone number can start with a zero.) * - The digits 0 and 1 do not have letters associated with them, so they should be left as numbers. * - Don't return every combination of those digits in any order, just the order given. * * Extra credit: There's a list of English dictionary words at /usr/share/dict/words . * Why not filter your results to only return words contained in that file? * var phoneDigitsToLetters = { 0: "0", 1: "1", 2: "ABC", 3: "DEF", 4: "GHI", 5: "JKL", 6: "MNO", 7: "PQRS", 8: "TUV", 9: "WXYZ", }; */ var telephoneWords = function (digitString) { let results = []; function recur(res2, count) { if (count === digitString.length) { results.push(res2.join("")); //가위바위보랑 달리, 각 문자들을 문자열로 합해줘야해서 join을 써줬다. } else { let i = count; //가위바위보는 for문을 써서, 재귀함수 돌때마다 다시 첫 문자들을 합쳐줬는데, 해당 문제는 주어진 인자에서 다시 앞으로 돌아가면 안된다. let chars = phoneDigitsToLetters[digitString[i]].split(""); chars.forEach((ele) => { recur(res2.concat(ele), count + 1); }); } } recur([], 0); return results; }; | cs |
728x90
'CS STUDY > Algorithm&Data structure' 카테고리의 다른 글
[JS]알고리즘 문제풀이6_재귀활용 (0) | 2020.11.08 |
---|---|
[JS]알고리즘 문제풀이5_bind( )함수 (0) | 2020.11.06 |
[JS]알고리즘 문제풀이3_재귀활용 (0) | 2020.11.06 |
[JS]알고리즘 문제풀이2_재귀활용 (0) | 2020.11.05 |
[JS]알고리즘 문제풀이1_해시테이블 활용 (0) | 2020.11.03 |