1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
| #include <vector> #include <string>
using std::vector; using std::string;
class Solution { private: vector<vector<char> > num2char = { {}, {}, { 'a', 'b', 'c' }, { 'd', 'e', 'f' }, { 'g', 'h', 'i' }, { 'j', 'k', 'l' }, { 'm', 'n', 'o' }, { 'p', 'q', 'r', 's' }, { 't', 'u', 'v' }, { 'w', 'x', 'y', 'z' }, };
void __letterCombinations(vector<int> &nums, vector<string> &res, string &curr, int pos) { int i, n = nums.size();
if (curr.size() == n) { res.push_back(curr); return; }
for (char ch : num2char[nums[pos]]) { curr.push_back(ch);
__letterCombinations(nums, res, curr, pos + 1);
curr.pop_back(); } }
public: vector<string> letterCombinations(string digits) { vector<string> res; vector<int> nums; string curr;
for (char ch : digits) nums.push_back(ch - '0');
__letterCombinations(nums, res, curr, 0);
return res; } };
|