Letter Combinations of a Phone Number
2013.12.6 19:52
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.
Solution:
Given a certain digit string and the corresponding mapping between digits [0-9] and letters [a-z], return all the possible letter combinatios that map to this digit string. Since all the combinations must be enumerated, using DFS is efficient in coding. A mapping array between digits and letters is needed.
Code segment is quite short and need no more explanation.
Time complexity is BIG_PI(i in range(0, len(digit_str))){number of mapping for digit_str[i]}, space complexity is O(len(digit_str)).
Accepted code:
1 // 7CE, 2RE, 1WA, 1AC, too bad~ 2 #include <string> 3 using namespace std; 4 5 class Solution { 6 public: 7 vector<string> letterCombinations(string digits) { 8 // IMPORTANT: Please reset any member data you declared, as 9 // the same Solution instance will be reused for each test case. 10 result.clear(); 11 12 dfs(digits, 0, ""); 13 14 return result; 15 } 16 private: 17 vector<string> result; 18 string dict[10] = { 19 " ", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" 20 }; 21 22 void dfs(string &digits, int idx, string str) { 23 if(idx == digits.length()){ 24 result.push_back(str); 25 // 1RE here, didn't return 26 return; 27 } 28 29 // 7CE here, dict[digits[idx] - '0'], type mismatch 30 for(int i = 0; i < dict[digits[idx] - '0'].length(); ++i){ 31 // 1RE here, 1WA here, wrong index 32 dfs(digits, idx + 1, str + dict[digits[idx] - '0'][i]); 33 } 34 } 35 };