Given a string containing digits from 2-9
inclusive, 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. Note that 1 does not map to any letters.
Example:
Input: "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.
思路:回溯法
1 class Solution { 2 private: 3 // 创建映射map 4 unordered_map<char, string> num2char {{'2', "abc"}, {'3', "def"}, {'4', "ghi"}, {'5', "jkl"}, 5 {'6', "mno"}, {'7', "pqrs"}, {'8', "tuv"}, {'9', "wxyz"}}; 6 7 void letterCombinations(vector<string> &res, string &combination, string digits, int index, int len) { 8 if (index == len) { 9 res.push_back(combination); 10 return; 11 } 12 //遍历第index位可以选择的字符 13 for (char c : num2char[digits[index]]) { 14 combination.push_back(c); 15 letterCombinations(res, combination, digits, index + 1, len); 16 combination.pop_back(); 17 } 18 /* 19 string current = num2char[digits[index]]; 20 for (int i = 0; i < current.length(); i++) { 21 combination.push_back(current[i]); 22 letterCombinations(res, combination, digits, index + 1, len); 23 combination.pop_back(); 24 } */ 25 } 26 public: 27 vector<string> letterCombinations(string digits) { 28 29 int len = digits.length(); 30 vector<string> res; 31 if (len == 0) { 32 return res; 33 } 34 35 string combination; 36 letterCombinations(res, combination, digits, 0, len); 37 return res; 38 } 39 };