初学LeetCode算法题电话号码的字母组合(虽然不难但是做出来还是很爽的)

2022-12-26 15:55:30 浏览数 (1)

代码语言:javascript复制
 * @param {string} digits
 * @return {string[]}
 * 输入:"23"
 * 输出:["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
 */
var letterCombinations = function (digits) {
    //存储键盘值
    if(digits==""){
        return 
    }
    let code = ["", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"]
    let str = digits.split("")
    let newCode = []
    for (let i = 0, len = str.length; i < len; i  ) {
        newCode.push(code[str[i]])
    }
    let count = (newCode) => {
        let arr = []
        if(newCode.length==1){
            for(i=0,iL=newCode[0].length;i<iL;i  ){
                arr.push(newCode[0][i])
            }
            return arr
        }
        for (let k = 0, KLen = newCode[0].length; k < KLen; k  ) {
            for (let j = 0, jLen = newCode[1].length; j < jLen; j  ) {
                arr.push(`${newCode[0][k]}${newCode[1][j]}`)
            }
        }
        newCode.splice(0, 2, arr)
        if (newCode.length > 1) {
            count(newCode)
        }
        return newCode[0]
    }
   return count(newCode)
   

};
console.log(letterCombinations("23"))
ode

0 人点赞