From : https://leetcode.com/problems/letter-combinations-of-a-phone-number/
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"].
class Solution {
public:
vector<string> letterCombinations(string digits) {
vector<string> ans;
if(digits == "") return ans;
map<char, string> charts;
charts['2'] = "abc";
charts['3'] = "def";
charts['4'] = "ghi";
charts['5'] = "jkl";
charts['6'] = "mno";
charts['7'] = "pqrs";
charts['8'] = "tuv";
charts['9'] = "wxyz";
find(ans, digits, charts, "", 0);
return ans;
}
void find(vector<string>& ans, string dgits, map<char, string>& chts, string cur, int idx) {
if(cur.size() == dgits.size()) { ans.push_back(cur); return; }
string str = chts[dgits[idx]];
for(int i=0, sz=str.size(); i<sz; i++) {
cur += str[i];
find(ans, dgits, chts, cur, idx+1);
cur.pop_back();
}
}
};