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.
用一个array保存数字对应的字符,再用dfs枚举所有解
1 class Solution { 2 private: 3 map<char, vector<char> > dict; 4 vector<string> ret; 5 public: 6 void createDict() 7 { 8 dict.clear(); 9 dict['2'].push_back('a'); 10 dict['2'].push_back('b'); 11 dict['2'].push_back('c'); 12 dict['3'].push_back('d'); 13 dict['3'].push_back('e'); 14 dict['3'].push_back('f'); 15 dict['4'].push_back('g'); 16 dict['4'].push_back('h'); 17 dict['4'].push_back('i'); 18 dict['5'].push_back('j'); 19 dict['5'].push_back('k'); 20 dict['5'].push_back('l'); 21 dict['6'].push_back('m'); 22 dict['6'].push_back('n'); 23 dict['6'].push_back('o'); 24 dict['7'].push_back('p'); 25 dict['7'].push_back('q'); 26 dict['7'].push_back('r'); 27 dict['7'].push_back('s'); 28 dict['8'].push_back('t'); 29 dict['8'].push_back('u'); 30 dict['8'].push_back('v'); 31 dict['9'].push_back('w'); 32 dict['9'].push_back('x'); 33 dict['9'].push_back('y'); 34 dict['9'].push_back('z'); 35 } 36 37 void dfs(int dep, int maxDep, string &s, string ans) 38 { 39 if (dep == maxDep) 40 { 41 ret.push_back(ans); 42 return; 43 } 44 45 for(int i = 0; i < dict[s[dep]].size(); i++) 46 dfs(dep + 1, maxDep, s, ans + dict[s[dep]][i]); 47 } 48 49 vector<string> letterCombinations(string digits) { 50 // Start typing your C/C++ solution below 51 // DO NOT write int main() function 52 ret.clear(); 53 createDict(); 54 dfs(0, digits.size(), digits, ""); 55 return ret; 56 } 57 };