LeetCode-17.电话号码的字母组合
看到这道题的第一眼就感觉可以暴力枚举,直接去遍历所有数字,然后对每个数字对应的包含3或4个字符的字符串进行遍历,把答案容器中已有的字符串和遍历的这些字符进行组合得到最新的答案。
按照这种思路进行编码,我把核心的代码写成了一个子函数,数字和字母的对应关系使用map或者说字典这种数据结构进行存储。第一次编写的时候心不在焉,出错了。删掉重写,一次AC。
看完题解,发现是用的回溯法,基本想法和思路感觉和我的解法没有太大的差别,但是回溯法三个字听起来就好厉害,希望下次自己也能想到这种写法吧!看到中等难度就不想动脑子,什么数据结构和算法都根本不管,直接就暴力,这种想法还是不要有。
这个所谓的回溯法感觉就是深度优先算法啊。要好好想想。
附上自己的代码吧,时间复杂度有点高,空间复杂度感觉还行。
class Solution {
private:
map<char, string> dict{{'2',"abc"},
{'3',"def"},
{'4',"ghi"},
{'5',"jkl"},
{'6',"mno"},
{'7',"pqrs"},
{'8',"tuv"},
{'9',"wxyz"}};
public:
vector<string> letterCombinations(string digits) {
vector<string> ans;
if(digits.length()==0)
return ans;
char ch;
for(int i=0; i<digits.length(); i++){
ch=digits[i];
string ch_str=dict[ch];
ans = fun(ch_str, ans);
}
return ans;
}
vector<string> fun(string& str, vector<string>& vec){
vector<string> temp_ans;
if(vec.size()==0){
string s="#";
for(int i=0; i<str.length(); i++){
s[0]=str[i];
temp_ans.push_back(s);
}
}
else{
string s="#";
for(int i=0; i<str.length(); i++){
s[0]=str[i];
for(int j=0; j<vec.size(); j++){
string s2=vec[j];
temp_ans.push_back(s2+s);
}
}
}
return temp_ans;
}
};