使用DFS递归实现,遍历解空间树:
#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
#include<unordered_map>
using namespace std;
class Solution
{
public:
vector<string> letterCombinations(string& digits)
{
static unordered_map<string,string> NumLetter;
NumLetter.insert(make_pair("0"," "));
NumLetter.insert(make_pair("1"," "));
NumLetter.insert(make_pair("2","abc"));
NumLetter.insert(make_pair("3","def"));
NumLetter.insert(make_pair("4","ghi"));
NumLetter.insert(make_pair("5","jkl"));
NumLetter.insert(make_pair("6","mno"));
NumLetter.insert(make_pair("7","pqrs"));
NumLetter.insert(make_pair("8","tuv"));
NumLetter.insert(make_pair("9","wxyz"));
static vector<string> Result;
Result.clear();
string currstring="";
DFSTraversal(digits,NumLetter,0,currstring,Result);
return Result;
}
void DFSTraversal(string& digits, unordered_map<string,string>& numletter,
int no, string& prestring, vector<string>& result)
{
int i=0;
string index;
string nextnumstring;
string nextnumletter;
string currstring;
if(no==digits.length())
{
result.push_back(prestring);
return;
}
/*..................................*/
index=digits.substr(no,1);
unordered_map<string,string>::iterator it= numletter.find(index);
nextnumstring=it->second;
for(i=0;i<nextnumstring.size();i++)
{
nextnumletter=nextnumstring.substr(i,1);
currstring=prestring+nextnumletter;
DFSTraversal(digits,numletter,no+1,currstring,result);
}
return;
}
};