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.git
Input:Digit string "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].app
题目的意思是给咱们一个数字字符串Digit String,以后咱们须要输出他们的所有的组合.
解决这道题目的思路就是用深度遍历.函数
而后咱们来看一下具体的思路,假如给定的字符串是“234”;
2:[a, b, c]
3:[d, e, f]
4:[g, h, i]spa
咱们想要输出这样的所有组合,怎么作呢?
首先 咱们定义一个res为空,符合条件的组合都放在里面,而后定义一个temp为空,来存储每次遍历符合条件的一个字符串.code
过程是这样的,首先
temp.push(a);
temp.push(d);
temp.push(g);
此时长度为digits.length;把temp加到res里面.
此时res=[‘adg’]
以后temp.pop()
temp.push(h)
长度为digits.length;temp加到res里面.
res =['adg', 'beh'];
temp.pop();
temp.push(i)
长度 == digits.length temp加到res里面
res = [‘adg’, 'bdh', 'adi'];
.....
就照着这样执行下去,而后就能遍历完全部的组合.递归
不知道这样讲会不会清楚,若是不清楚,能够留言,我会回复的.图片
var dict = { // 定义一个键盘的字典 "2": "abc", "3": "def", "4": "ghi", "5": "jkl", "6": "mno", "7": "pqrs", "8":"tuv", "9":"wxyz" }; var letterCombinations = function(digits) { if (digits.length == 0) return []; var res = []; dfs(res, digits, 0, []); return res; }; var dfs = function(res, digits, index, temp) { 递归函数 if (temp.length == digits.length) { res.push(temp.join('')); return; } // dict[digits[index]]就是当前循环的数字对应的字符串. for (let i = 0; i < dict[digits[index]].length; i++) { temp.push(dict[digits[index]][i]); dfs(res, digits, index+1, temp); // index+1表明要循环下一个数字 temp.pop(); // 每次执行完当前的dfs以后,要pop一下,这样才能继续下一次循环 } }