链接
思路
-
首先我们要先得到 "电话号码" 所对应的 返回数组
-
根据得到的返回数组,去进行拼接,但是 js 和 c 语言不一样,需要借助 .charCodeAt(0) 来获取到当前的 ASCII 码
-
注意屏幕说的是 要 给的 最后长度的 结果,所以我们在遍历到 最后一位的时候,记录下来即可,如果不是就继续递归
代码:
javascript
/**
* @param {string} digits
* @return {string[]}
*/
var letterCombinations = function (digits) {
let res = [], len = digits.length
function getChar(char) {
switch (char) {
case '2': return new Array(3).fill().map((value, index) => String.fromCharCode('a'.charCodeAt(0) + index));
case '3': return new Array(3).fill().map((value, index) => String.fromCharCode('d'.charCodeAt(0) + index));
case '4': return new Array(3).fill().map((value, index) => String.fromCharCode('g'.charCodeAt(0) + index));
case '5': return new Array(3).fill().map((value, index) => String.fromCharCode('j'.charCodeAt(0) + index));
case '6': return new Array(3).fill().map((value, index) => String.fromCharCode('m'.charCodeAt(0) + index));
case '7': return new Array(4).fill().map((value, index) => String.fromCharCode('p'.charCodeAt(0) + index));
case '8': return new Array(3).fill().map((value, index) => String.fromCharCode('t'.charCodeAt(0) + index));
case '9': return new Array(4).fill().map((value, index) => String.fromCharCode('w'.charCodeAt(0) + index));
}
}
function getRes(pre, index) {
if (index >= len) return
else if (index === len - 1) {
res.push(...getChar(digits[index]).map(value => {
return pre + value
}))
}
else getChar(digits[index]).forEach(value => {
getRes(pre + value, index + 1)
})
}
getRes('', 0)
return res
};