標籤:
Letter Combinations of a Phone Number Total Accepted: 40709 Total Submissions: 157759My SubmissionsQuestion Solution
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.
https://leetcode.com/problems/letter-combinations-of-a-phone-number/ 提示說是高貴的回溯,說白了就是遞迴...思路很簡單,比如給定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); //clone25 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 };
[LeetCode][JavaScript]Letter Combinations of a Phone Number