Leetcode C++《热题 Hot 100-27》17.电话号码的字母组合
写的代码超时了,正准备绞尽脑汁看怎么优化,突然发现怎么代码里面
- 题目
给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。
给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。
示例:
输入:“23”
输出:[“ad”, “ae”, “af”, “bd”, “be”, “bf”, “cd”, “ce”, “cf”].
说明:
尽管上面的答案是按字典序排列的,但是你可以任意选择答案输出的顺序。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/letter-combinations-of-a-phone-number
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
- 思路
- 方案1: 参考树的层次遍历,逐步接近答案,时间复杂度是3+9+27+… +3^(digits.size()) 【等比数列求和】
- 方案2:使用dfs,不需要构建树,直接dfs递归大法即可。参考https://leetcode-cn.com/problems/letter-combinations-of-a-phone-number/solution/17dian-hua-hao-ma-de-zi-mu-zu-he-shi-yong-shen-du-/,时间复杂度相差不大【相当于把整颗树都要遍历一遍】
- 代码
class Solution {
public:
vector<string> letterCombinations(string digits) {
map<char, string> temp;
int index = 0;
for (int i = 2; i < 10; i++ ) {
char num = (char)(i+'0');
string str = "";
for (int j = 0; j < 3; j++ ) {
str += (char) (index + j+'a');
}
if (i == 7 || i == 9) {
str += (char) (index + 3 +'a');
index += 4;
}
else {
index += 3;
}
temp.insert(make_pair(num, str));
}
vector<string> oneLevelStr;
vector<string> nextLevelStr;
if (digits.length() == 0)
return oneLevelStr;
oneLevelStr.push_back("");
for (int i = 0; i < digits.length(); i++) {
nextLevelStr.clear();
for (int j = 0; j < oneLevelStr.size(); j++) {
string childStr = temp[digits[i]];
for (int k = 0; k < childStr.length(); k++) {
nextLevelStr.push_back(oneLevelStr[j]+childStr.substr(k, 1));
}
}
oneLevelStr.assign(nextLevelStr.begin(), nextLevelStr.end());
}
return oneLevelStr;
}
};