解法1: 用map和vector。
假设输入是"23",先把2对应的"abc"分别写到retVec里面,即retVec={"a","b","c"}。然后程序处理3时,把3对应的"def"分别append到retVec的各个元素后面,也就是retVec={"a","b","c","ad","ae","af","bd","be","bf","cd","ce","cf"}。然后再将之前的"a","b","c"删掉,这样retVec就只剩下{"ad","ae","af","bd","be","bf","cd","ce","cf"}了。
#include <iostream>
#include <map>
#include <vector>
using namespace std;
map<char, string> phoneMap = {{'2',"abc"},{'3',"def"},{'4',"ghi"},{'5',"jkl"},{'6',"mno"},{'7',"pqrs"},{'8',"tuv"},{'9',"wxyz"}};
vector<string> letterCombinations(string digits) {
vector<string> retVec;
for (auto it=digits.begin(); it<digits.end(); ++it) {
char c=(char)(*it);
if ((c>='2') && (c<='9')) {
size_t len=retVec.size();
if (!len) {
for (int i=0; i<phoneMap[c].size(); ++i) {
retVec.push_back(phoneMap[c].substr(i,1));
}
}else {
for (int i=0; i<len; ++i) {
for (int j=0; j<phoneMap[c].size(); ++j) {
string tmp=retVec[i];
retVec.push_back(tmp.append(1, phoneMap[c].at(j)));
}
}
retVec.erase(retVec.begin(), retVec.begin()+len);
}
}
}
return retVec;
}
int main()
{
string phoneNum1="23";
vector<string> ret1=letterCombinations(phoneNum1);
cout<<"phoneNum1="<<phoneNum1<<endl;
for (auto it=ret1.begin(); it<ret1.end(); it++) {
cout<<*it<<endl;
}
return 0;
}
解法2:DFS
class Solution {
public:
/**
* @param digits: A digital string
* @return: all posible letter combinations
*/
vector<string> letterCombinations(string &digits) {
if (digits.size() == 0) return {};
string sol = "";
vector<string> sols;
helper(digits, 0, sol, sols);
return sols;
}
private:
map<char, vector<char>> dict = {{'2', {'A', 'B', 'C'}}, {'3', {'D', 'E', 'F'}},
{'4', {'G', 'H', 'I'}}, {'5', {'J', 'K', 'L'}},
{'6', {'M', 'N', 'O'}}, {'7', {'P', 'Q', 'R', 'S'}},
{'8', {'T', 'U', 'V'}}, {'9', {'W', 'X', 'Y', 'Z'}}};
void helper(string &digits, int pos, string &sol, vector<string> &sols) {
if (sol.size() == digits.size()) {
sols.push_back(sol);
}
for (int i = pos; i < digits.size(); ++i) {
for (int j = 0; j < dict[digits[i]].size(); ++j) {
sol = sol + (char)(dict[digits[i]][j] + ('a' - 'A'));
helper(digits, i + 1, sol, sols);
sol = sol.substr(0, sol.size() - 1);
}
}
}
};