[leetcode] 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.
Although the above answer is in lexicographical order, your answer could be in any order you want.
1 class Solution 2 { 3 private: 4 void Initialize() 5 { 6 letters.push_back(""); 7 letters.push_back(""); 8 letters.push_back("abc"); 9 letters.push_back("def"); 10 letters.push_back("ghi"); 11 letters.push_back("jkl"); 12 letters.push_back("mno"); 13 letters.push_back("pqrs"); 14 letters.push_back("tuv"); 15 letters.push_back("wxyz"); 16 } 17 public: 18 void dfs(int dep, int maxDep, string &s, string ans) 19 { 20 if(dep == maxDep) 21 { 22 ret.push_back(ans); 23 return; 24 } 25 26 for(int i=0; i<letters[s[dep]-'0'].size(); i++) 27 dfs(dep+1, maxDep, s, ans + letters[s[dep]-'0'][i]); 28 } 29 vector<string> letterCombinations(string digits) 30 { 31 char ch; 32 Initialize(); 33 ret.clear(); 34 35 if(digits != "") 36 dfs(0, digits.size(), digits, ""); 37 38 return ret; 39 } 40 41 private: 42 vector<string> letters; 43 vector<string> ret; 44 };