17. Letter Combinations of a Phone Number

Posted bubbleStar

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了17. Letter Combinations of a Phone Number相关的知识,希望对你有一定的参考价值。

Given a digit string, return all possible letter combinations that the number could represent.

A mapping of digit to letters (just like on the telephone buttons) is given below.

这是回溯问题(参考:http://blog.csdn.net/jarvischu/article/details/16067319)。

下面是javascript代码编写的递归版和迭代版的代码:

递归版:
var letterCombinations = function(digits) {
    var map = [\'\',\'\',\'abc\',\'def\',\'ghi\',\'jkl\',\'mno\',\'pqrs\',\'tuv\',\'wxyz\'];
    var result = [];
    backtrack(map, "", digits, result, 0);
    return result;
};
function backtrack(map, s, digits, result, start){
        
    if(digits.length === 0) return;
  
    if(s.length === digits.length){
         result.push(s);
         return;
    }
    else{
        for(var i = start; i < digits.length; i++){
          var index = digits[i] - \'0\';
           for(var j=0; j < map[index].length; j++){
             s = s + map[index][j];
             backtrack(map, s, digits, result, i+1);
             s = s.substring(0, s.length-1);
           }
         } 
     }  
}

 

以上是关于17. Letter Combinations of a Phone Number的主要内容,如果未能解决你的问题,请参考以下文章

17. Letter Combinations of a Phone Number

17. Letter Combinations of a Phone Number

17. Letter Combinations of a Phone Number

17. Letter Combinations of a Phone Number

17. Letter Combinations of a Phone Number

17. Letter Combinations of a Phone Number