[Problems] Given a string that contains only numbers 2-9, it can return all letter combinations indicated.
Given digital map to letters as follows (the same telephone key). Note 1 does not correspond to any alphabet.
Example:
Input: " 23 " Output: [ " AD " , " AE " , " AF " , " BD " , " BE " , " BF " , " CD " , " CE " , " CF2 " .] Description: Although the above the answer is based on lexicographic order, but you can choose the order of the answer output.
[Thinking] This is a retrospective issue of the Normal template, we first think back exit condition: the size and the size of the array digits us search out tmp_res phase exit at the same time, because we all share the function of each back tmp_res this variable, so after completion of the function call needs to be restored to its original state , namely:
tmp_res = I +
backtrace (......)
tmp_res.pop_back ()
wherein there are two parameters in the traceback function is varied, a character string is searched out, the other It is the digits of the index, because it is based on the numerical digits to select the add those letters! ! !
class Solution { public: void backtrace(vector<string>& res, string tmp_res, string digits, int idx){ // res为引用形式 if(tmp_res.length() == digits.length()){ res.push_back(tmp_res); return; } string str = table[digits[idx]]; for(auto i: str){ tmp_res += i; backtrace(res, tmp_res, digits, idx+1); tmp_res.pop_back(); } } vector<string> letterCombinations(string digits) { vector<string> res; if(digits == "") return res; backtrace(res, "", digits, 0); return res; } private: unordered_map<char, string> table{{'0', " "}, {'1',"*"}, {'2', "abc"}, {'3',"def"}, {'4',"ghi"}, {'5',"jkl"}, {'6',"mno"}, {'7',"pqrs"},{'8',"tuv"}, {'9',"wxyz"}}; };