思路
深度优先遍历,每次试探的是对应数字的对于字母,如
2 试探->>> abc
6 试探->>> mno
运用map装整个表, map<char,string> = {{}}; //c++11支持
核心部分
if(str.size()==digits.size())
终止条件 记录结果 res.push_back(str);
tmp = map[digits[k]];
for(auto w:tmp)
{
str.push_back(w);
递归
str.pop_back();回溯
}
代码
class Solution {
public:
map<char,string> table= {{'0',""},{'1',"*"},{'2',"abc"},{'3',"def"},{'4',"ghi"},
{'5',"jkl"},{'6',"mno"},{'7',"pqrs"},{'8',"tuv"},{'9',"wxyz"}};
vector <string> res;
void dfs(string digits,string str,int k)
{
if(str.size()==digits.size())
{
res.push_back(str);
}
string tmp = table[digits[k]];
for(auto w:tmp)
{
str+=w;
dfs(digits,str,k+1);
str.pop_back();
}
}
vector<string> letterCombinations(string digits) {
if(digits=="")
return res;
dfs(digits,"",0);
return res;
}
};