Open pwstrick opened 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(); } }
17. 电话号码的字母组合