思路:使用回溯法DFS。
class Solution {
public:
void digui(vector<string> &result, int depth, string digits,
string &ss, const int len, map<int, string> phone_num)
{
if (depth == len)
{
result.push_back(ss);
return;
}
int current = digits[depth]-'0';
for (auto s : (phone_num[current]))
{
string yuans = ss;
ss = ss + s;
digui(result, depth + 1, digits, ss, len, phone_num);
ss = yuans;
}
}
vector<string> letterCombinations(string digits)
{
//使用回溯方法进行解题
int len = digits.size();
vector<string> result;
if (len == 0)
return result;
string ss;
//使用map记录一下每个按键对应的字母
map<int, string> phone_num = { { 2,"abc" },{ 3,"def" },{ 4,"ghi" },
{ 5,"jkl" },{ 6,"mno"}, { 7,"pqrs" },
{ 8,"tuv" },{ 9,"wxyz" } };
int depth = 0;//先定义一个记录深度的变量,这样可以在满足条件的时候返回
digui(result, depth, digits, ss, len,phone_num);
return result;
}
};