题目地址:https://leetcode-cn.com/problems/letter-combinations-of-a-phone-number/
解题思路:暴力求解,很明显循环的个数根据digits的个数有关,所以我们可以采用递归来进行这种动态的多重循环。
class Solution { private: map<int, char> mp = { {2,'a'}, {3,'d'}, {4,'g'}, {5,'j'}, {6,'m'}, {7,'p'}, {8,'t'}, {9,'w'} }; vector<string> ans; void getAns(string result,int loc,char c,string digits) { if (loc == digits.size()) { ans.push_back(result + c); return; } int num = digits[loc] - '0' == 7 || digits[loc] - '0' == 9 ? 4 : 3; for (int i = 0; i < num; i++) getAns(result + c, loc+1, mp[digits[loc] - '0']+i, digits); } public: vector<string> letterCombinations(string digits) { int i; if (digits == "") return ans; else { int num = digits[0] - '0' == 7 || digits[0] - '0' == 9 ? 4 : 3; for (i = 0; i < num; i++) getAns("", 1, mp[digits[0] - '0'] + i, digits); } return ans; } };