recursion 활용한 또 다른 문제
이것도 가위바위보 문제의 변형으로 생각하고 풀면 될듯하다.
/*
* 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;
};