JavaScript | LeetCode | Search |. 17 monogram phone number

Method 1: backtracking backtracking
Read the answer
idea:

  1. Length of each string output equal to the input string length
  2. Length of the input string of the search tree corresponds to the depth (height)
  3. When the length of the string consisting of a length equal to the input string, the string should be added to the result set; was then added to the last character ¥ deleted, and a new character string and then join the same group ¥ Composition

Note : ¥ is a character code; refer to the same group on the same button on the keyboard

/** * @param {string} digits * @return {string[]} */
var letterCombinations = function(digits) {    
    if(digits == undefined || digits.length == 0) {        
        return [];    
    }    
    var keys = [];    
    keys.push(""); // 0    
    keys.push(""); // 1    
    keys.push("abc"); // 2    
    keys.push("def");    
    keys.push("ghi");    
    keys.push("jkl");    
    keys.push("mno");    
    keys.push("pqrs");    
    keys.push("tuv");    
    keys.push("wxyz");
    var output = [];    
    doCombination(output, "", keys, digits);    
    return output;
};

function doCombination(output, prefix, keys, digits) {    
    if(prefix.length == digits.length) {        
        output[output.length] = prefix;        
        return;    
    }    
    var i = 0, index = Number(digits[prefix.length]);
    // index:通过已有字符串prefix的长度,确定此时到了搜索树的第几层,即digits的哪一位        

    for(i = 0; i < keys[index].length; i++) { // 遍历相应层次字符        
        prefix += keys[index].charAt(i); // 衔接字符        
        doCombination(output, prefix, keys, digits);        
        prefix = prefix.substring(0, prefix.length - 1); // 去除字符    
    }
}
Released seven original articles · won praise 0 · Views 55

Guess you like

Origin blog.csdn.net/J_learner/article/details/104692479