- 题目:
给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。答案可以按 任意顺序 返回。 - 思路:
涉及到组合问题的时候一般都是采用回溯算法,这题相当于使用DFS的方法,每走一条路线最终积累的字符串就是得到的一个结果。 - 代码:
map<char,string> Map = { {'2',"abc"},{'3',"def"},{'4',"ghi"},
{'5',"jkl"},{'6',"mno"},{'7',"pqrs"},{'8',"tuv"},{'9',"wxyz"} };
vector<string> res;
string currentString;
vector<string> letterCombinations(string digits) {
if(!digits.size()){
return res;
}
DFS(digits);
return res;
}
void DFS(string digit){
if(!digit.size()){
res.push_back(currentString);
}else{
char num = digit[0];
string letter = Map[num];
for(int i = 0; i < letter.size();i++){
currentString.push_back(letter[i]);
DFS(digit.substr(1));
currentString.pop_back();
}
}
}
- 代码二:
class Solution {
public:
unordered_map<int,string> mymap{{2,"abc"},
{3,"def"},
{4,"ghi"},
{5,"jkl"},
{6,"mno"},
{7,"pqrs"},
{8,"tuv"},
{9,"wxyz"}};
vector<string> res;
string cur;
vector<string> letterCombinations(string digits) {
res.clear();
if (digits.size() == 0) {
return res;
}
dfs(digits,0);
return res;
}
void dfs(string digits,int i){
if(cur.size() == digits.size()){
res.push_back(cur);
return;
}
string temp = mymap[digits[i]-'0'];
for(auto t : temp){
cur.push_back(t);
dfs(digits,i+1);
cur.pop_back();
}
}
};
- tips:
在涉及到组合操作时使用回溯算法。