leetcode--17. 电话号码的字母组合--深度遍历优先
给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。答案可以按 任意顺序 返回。
给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。
示例 1:
输入:digits = "23"
输出:["ad","ae","af","bd","be","bf","cd","ce","cf"]
示例 2:
输入:digits = ""
输出:[]
示例 3:
输入:digits = "2"
输出:["a","b","c"]
提示:
0 <= digits.length <= 4
digits[i] 是范围 ['2', '9'] 的一个数字。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/letter-combinations-of-a-phone-number
解析:深度遍历优先一遍就可以得出结果。在数据结构讲树的部分时候,深度遍历优先是用于树的先序遍历。要将视野放的广一些,对于顺序的组合问题也是可以建成树的,并且是在树的叶子节点得到结果的。
#include<iostream>
#include<vector>
#include<map>
using namespace std;
vector<string> res;
map<string, vector<string>> alphaTable;
void createAlphaTable() {
//pair<string, vector<string>> temp;
alphaTable.insert(make_pair("2", vector<string>{"a", "b", "c"}));
alphaTable.insert(make_pair("3", vector<string>{"d", "e", "f"}));
alphaTable.insert(make_pair("4", vector<string>{"g", "h", "i"}));
alphaTable.insert(make_pair("5", vector<string>{"j", "k", "l"}));
alphaTable.insert(make_pair("6", vector<string>{"m", "n", "o"}));
alphaTable.insert(make_pair("7", vector<string>{"p", "q", "r", "s"}));
alphaTable.insert(make_pair("8", vector<string>{"t", "u", "v"}));
alphaTable.insert(make_pair("9", vector<string>{"w", "x", "y", "z"}));
}
void dfs(string digits, string result) {
if (digits == "" && result !="") {
res.push_back(result);
}
string begin = digits.substr(0,1);
for (auto i : alphaTable[begin]) {
string temp = result + i;
dfs(digits.substr(1), temp);
}
}
int main() {
string input;
cin >> input;
createAlphaTable();
dfs(input, "");
for (auto i : res)
cout << i << " ";
}
class Solution {
public:
map<string, vector<string>> alphaTable;
vector<string> res;
void createAlphaTable() {
//pair<string, vector<string>> temp;
alphaTable.insert(make_pair("2", vector<string>{"a", "b", "c"}));
alphaTable.insert(make_pair("3", vector<string>{"d", "e", "f"}));
alphaTable.insert(make_pair("4", vector<string>{"g", "h", "i"}));
alphaTable.insert(make_pair("5", vector<string>{"j", "k", "l"}));
alphaTable.insert(make_pair("6", vector<string>{"m", "n", "o"}));
alphaTable.insert(make_pair("7", vector<string>{"p", "q", "r", "s"}));
alphaTable.insert(make_pair("8", vector<string>{"t", "u", "v"}));
alphaTable.insert(make_pair("9", vector<string>{"w", "x", "y", "z"}));
}
void dfs(string digits, string result) {
if (digits == "" && result !="") {
res.push_back(result);
}
string begin = digits.substr(0,1);
for (auto i : alphaTable[begin]) {
string temp = result + i;
dfs(digits.substr(1), temp);
}
}
vector<string> letterCombinations(string digits) {
createAlphaTable();
dfs(digits, "");
return res;
}
};