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"].
#include<iostream> #include<algorithm> #include<string> #include<vector> using namespace std; //递归方法,每次选一个当前数字对应的字母,下次选择下一个数字对应的字母, //当选择数量达到给定数字串长度时,作为一个结果加入到结果集里。 class Solution { public: void letterCombinations_aux(int step, string& path, vector<string>& ans, const string& digits) { const static string strT[10] = { "", "", "abc", "def", "ghi", "jkl", "mno", "qprs", "tuv", "wxyz" }; if (step == digits.size()) //递归终止条件:选择数量达到给定数字串长度 { ans.push_back(path); return; } for (int i = 0; i < strT[digits[step] - '0'].size(); ++i) { path.push_back(strT[digits[step] - '0'][i]); letterCombinations_aux(step + 1, path, ans, digits); path.pop_back(); } } vector<string> letterCombinations(string digits) { // Start typing your C/C++ solution below // DO NOT write int main() function string path; vector<string> ans; int step = 0; letterCombinations_aux(step, path, ans, digits); return ans; } }; int main() { const string s1 = "23"; Solution sol; vector<string> ans1; ans1 = sol.letterCombinations(s1); for (int i = 0; i < ans1.size(); i++) { cout << ans1[i]<<','; } system("pause"); return 0; }