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

來源:互聯網
上載者:User

標籤:

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.