给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。
给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。
示例:
输入:"23"
输出:["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
思路:
用一个队列直接去不断生成即可
class Solution {
public:
vector<string> letterCombinations(string digits) {
unordered_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;
if(digits.size() == 0) return res;
// 用队列完成排列的生成
queue<string> q;
q.push("");
for(auto d:digits){
int q_size = q.size();
string add = table[d];
for(int i = 0;i < q_size;i++){
string cur = q.front();
q.pop();
for(auto num:add){
q.push(cur+num);
}
}
}
while(!q.empty()){
res.push_back(q.front());
q.pop();
}
return res;
}
};