题目
解法 BFS + hash
/*
广度遍历,利用队列实现
*/
class Solution {
private:
unordered_map<char,string> tel_map;
queue <string> re_queue;
vector<string> result;
public:
Solution()
{
tel_map = {{'2',"abc"},{'3',"def"},{'4',"ghi"},{'5',"jkl"},{'6',"mno"},{'7',"pqrs"},{'8',"tuv"},{'9',"wxyz"}};
}
vector<string> letterCombinations(string digits) {
if(digits.length() == 0)
return result;
auto p = tel_map.find(digits[0]);
string tmp1 = p->second;
for(int i = 0 ; i < tmp1.length();i++)
{
string tmp2;
tmp2.push_back(tmp1[i]);
re_queue.push(tmp2);
}
for(int i = 1 ; i < digits.length();i++)
{
unordered_map<char,string>::iterator p = tel_map.find(digits[i]);
string tmp3 = p->second;
vector <string> tmp4;
while(!re_queue.empty())
{
string tmp5 = re_queue.front();
re_queue.pop();
for(int j = 0 ; j < tmp3.length();j++)
{
string tmp6 = tmp5 + tmp3[j];
tmp4.push_back(tmp6);
}
}
for(int k = 0; k < tmp4.size();k++)
{
re_queue.push(tmp4[k]);
}
}
while(!re_queue.empty())
{
result.push_back(re_queue.front());
re_queue.pop();
}
return result;
}
};
时间复杂度为 O ( 3 N ∗ 4 M ) O(3^N * 4^M) O(3N∗4M) N + M为输入数字的总数。