[LeetCode][JavaScript]Letter Combinations of a Phone Number

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.

Input:Digit string "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].

Note:
Although the above answer is in lexicographical order, your answer could be in any order you want.

 
 
 

 
 
提示说是高贵的回溯,说白了就是递归...
思路很简单,比如给定4个数字,就是个4重循环。
但是几重循环是动态的,递归嵌套一下就好了。
 1 /**
 2  * @param {string} digits
 3  * @return {string[]}
 4  */
 5 var letterCombinations = function(digits) {
 6     var dict = {};
 7     dict['2'] = ['a', 'b', 'c'];
 8     dict['3'] = ['d', 'e', 'f'];
 9     dict['4'] = ['g', 'h', 'i'];
10     dict['5'] = ['j', 'k', 'l'];
11     dict['6'] = ['m', 'n', 'o'];
12     dict['7'] = ['p', 'q', 'r', 's'];
13     dict['8'] = ['t', 'u', 'v'];
14     dict['9'] = ['w', 'x', 'y', 'z'];
15 
16     var target = [];
17     var i, j;
18     for(i in digits){
19         target.push(dict[digits[i]]);
20     }
21     return combinations(target);
22 
23     function combinations(arr){
24         var newArr = arr.slice(0); //clone
25         if(newArr.length === 0){
26             return [];
27         } else {
28             var res = [];
29             var top = newArr.shift();
30             var ret = combinations(newArr);
31             if(ret.length === 0){
32                 res = top;
33             }else{
34                 for(i = 0; i < top.length; i++){
35                     for(j = 0; j < ret.length; j++){
36                         res.push(top[i] + ret[j]);
37                     }
38                 }
39             }
40             return res;
41         }
42     }
43 };
 
 
 
 
 
 
 
 
原文地址:https://www.cnblogs.com/Liok3187/p/4553459.html