首页 > 试题广场 >

电话字母的组合

[编程题]电话字母的组合
  • 热度指数:9383 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解
给出一个仅包含数字的字符串,给出所有可能的字母组合。
数字到字母的映射方式如下:(就像电话上数字和字母的映射一样)

Input:Digit string "23"Output:["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
注意:虽然上述答案是按字典序排列的,但你的答案可以按任意的顺序给出
示例1

输入

"23"

输出

["ad","ae","af","bd","be","bf","cd","ce","cf"]
/**
  * 
  * @param digits string字符串 
  * @return string字符串一维数组
  */
function letterCombinations( digits ) {
    // write code here
    let phone = {
        2: ['a', 'b', 'c'],
        3: ['d', 'e', 'f'],
        4: ['g', 'h', 'i'],
        5: ['j', 'k', 'l'],
        6: ['m', 'n', 'o'],
        7: ['p', 'q', 'r', 's'],
        8: ['t', 'u', 'v'],
        9: ['w', 'x', 'y', 'z'],
    }
    let res = [];
    function backtrack(combination, next_digits){
        if(next_digits.length === 0){//如果数字串为空,则将当前字母组合插入到res
            res.push(combination);
        }
        else{
            for(let letter of phone[next_digits[0]]){//从数字串第一个数字开始循环处理
                backtrack(combination + letter, next_digits.substring(1));//将第一个数字的字母组合分别插入combination,再递归处理去掉首个数字剩下的数字串
            }
        }
    }
    if(digits){
        backtrack('', digits);//回溯函数入口
    }else{
        return [""];
    }
    return res;
}
module.exports = {
    letterCombinations : letterCombinations
};


编辑于 2020-08-24 22:00:05 回复(0)