pwstrick / daily

一份搜集的前端面试题目清单、面试相关以及各类学习的资料(不局限于前端)
2.39k stars 242 forks source link

电话号码的字母组合 #1059

Open pwstrick opened 4 years ago

pwstrick commented 4 years ago

17. 电话号码的字母组合

/**
 * @param {string} digits
 * @return {string[]}
 */
const chars = [
        ["a", "b", "c"],
        ["d", "e", "f"],
        ["g", "h", "i"],
        ["j", "k", "l"],
        ["m", "n", "o"],
        ["p", "q", "r", "s"],
        ["t", "u", "v"],
        ["w", "x", "y", "z"]
];
let results;
var letterCombinations = function(digits) {
    if(digits.length == 0)
        return [];
    results = [];
    digits = digits.split("").map(value => parseInt(value) - 2).filter(value => value >= 0);
    let route = [];
    backtrack(route, digits);
    return results;
};

function backtrack(route, digits) {
    if(digits.length == 0) {
        results.push(route.join(""));
        return;
    }
    let digit = digits.shift();
    for(let char of chars[digit]) {
        route.push(char);
        backtrack(route, [...digits]);  //复制一份数组 以免原始数组被修改
        route.pop();
    }
}