电话号码的字母组合

链接

17. 电话号码的字母组合 - 力扣(LeetCode)

思路

  1. 首先我们要先得到 "电话号码" 所对应的 返回数组

  2. 根据得到的返回数组,去进行拼接,但是 js 和 c 语言不一样,需要借助 .charCodeAt(0) 来获取到当前的 ASCII 码

  3. 注意屏幕说的是 要 给的 最后长度的 结果,所以我们在遍历到 最后一位的时候,记录下来即可,如果不是就继续递归

代码:

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
};
相关推荐
黄河123长江6 分钟前
有限Abel群的结构()
算法
名字还没想好☜40 分钟前
Go 的 time.After 在 select 循环里内存泄漏:定时器堆积原理与 timer.Reset 正确姿势
java·数据库·golang·go·goroutine
Jerry1 小时前
LeetCode 92. 反转链表 II
算法
骊城英雄1 小时前
Rust从入门到精通-trait
人工智能·算法·rust
圆山猫1 小时前
[Virtualization](三):RISC-V H-extension 与 Guest 执行模式
android·java·risc-v
caishenzhibiao1 小时前
期货先行者主图 同花顺期货通指标
java·c语言·c#
史呆芬1 小时前
分布式事务实战:微服务跨服务数据一致性解决方案
java·后端·spring cloud
可编程芯片开发2 小时前
基于PI控制算法的pwm直流电机控制系统Simulink建模与仿真
算法
IT界的老黄牛2 小时前
限流命中后该怎么办:直接丢、阻塞等待、延迟重投三种姿势的取舍
java·rocketmq·redisson·令牌桶·削峰·分布式限流
怕浪猫2 小时前
2840亿参数只卖白菜价:DeepSeek V4 Flash 正式版上线,Agent 能力暴涨6倍
人工智能·算法