数组版本
哈希版本:
一、17. 电话号码的字母组合
给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。答案可以按 任意顺序 返回。
给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。
示例 1:
输入:digits = "23" 输出:["ad","ae","af","bd","be","bf","cd","ce","cf"]
注意点:通过下标indx进行控制了就不需要在主函数中写出一个for循环了下面是刚开始写的main中有个for循环,dfs里还有个for循环,糟糕的很,dfs就使用了下标进行更替,不需要自己在胡乱搞
错解!!!
数组版本
class Solution {
public:
//也可以使用哈希映射
//map<char, string> mp = {{'2',"abc"}, {'3', "def"}, {'4', "ghi"}………………}
vector<string> vv = {"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
vector<string> res;
string temp;
void dfs(string digits, int indx)
{
if(indx==digits.size())//下标到达的位置为digit.size()
{
res.push_back(temp);
return;
}
int num = digits[indx]-'0'; // indx为字符串中的下标需要转化为数字
for(int i = 0; i < vv[num].size(); i++)
{
temp+=vv[num][i];
dfs(digits, indx+1); // dfs下一个下标位置
temp.pop_back(); //回退
}
}
vector<string> letterCombinations(string digits) {
if(digits.empty())
return res;
dfs(digits, 0);
return res;
}
};
哈希版本:
class Solution {
public:
map<char, string> mp = {{'2',"abc"},{'3',"def"},{'4',"ghi"},{'5',"jkl"},{'6',"mno"},{'7',"pqrs"},{'8',"tuv"},{'9',"wxyz"}};
vector<string> res;
string temp;
void dfs(string digits, int index)
{
if(index == digits.size())
{
res.push_back(temp);
return;
}
for(int i = 0; i < mp[digits[index]].size(); i++)
{
temp += mp[digits[index]][i];
dfs(digits, index+1);
temp.pop_back();
}
}
vector<string> letterCombinations(string digits) {
if(digits.empty())return res;
dfs(digits, 0);
return res;
}
};