目录
代码(三刷debug on answer 2024年3月7日)
题目:
代码(首刷看解析 **不熟练):
class Solution {
public:
vector<string> letterCombinations(string digits) {
vector<string> combinations;//最终答案的字符数组
if(digits.empty()) return combinations;
unordered_map<char, string> phoneMap{
{'2', "abc"},
{'3', "def"},
{'4', "ghi"},
{'5', "jkl"},
{'6', "mno"},
{'7', "pqrs"},
{'8', "tuv"},
{'9', "wxyz"}
};
string combination;//单个字符串
backtrace(combinations,phoneMap,digits,0,combination);//回溯函数
return combinations;
}
void backtrace(vector<string>& combinations,const unordered_map<char,string>& phoneMap,string digits,int index,string& combination){
if(index==digits.size()){
combinations.emplace_back(combination);
}else{
char digit=digits[index];
const string& letters = phoneMap.at(digit);
for(auto letter:letters){
combination.push_back(letter);
backtrace(combinations,phoneMap,digits,index+1,combination);
combination.pop_back();//去除字符后的字母
}
}
}
};
代码(二刷自解 2024年2月1日)
class Solution {
private:
vector<string> res;
string path;
unordered_map<char,string> hash{
{'2',"abc"}, {'3',"def"},
{'4',"ghi"}, {'5',"jkl"}, {'6',"mno"},
{'7',"pqrs"},{'8',"tuv"}, {'9',"wxyz"}
};
public:
void backtracking(string digits, int n) {
if (n == digits.size()) {
res.push_back(path);
return;
}
for (int i = 0; i < hash[digits[n]].size(); ++i) {
path += hash[digits[n]][i];
backtracking(digits, n + 1);
path.pop_back();
}
return;
}
vector<string> letterCombinations(string digits) {
if (digits.size() == 0) return res;
backtracking(digits,0);
return res;
}
};
代码(三刷debug on answer 2024年3月7日)
class Solution {
public://回溯
vector<string> result;
string paths;
// 数字字母映射表
unordered_map<char, string> digit_to_char{
{'0',""},
{'1',""}, {'2',"abc"},{'3',"def"},
{'4',"ghi"}, {'5',"jkl"},{'6',"mno"},
{'7',"pqrs"},{'8',"tuv"},{'9',"wxyz"}
};
void backtracking(string digits,int Rindex){
// 返回条件: d.size() == paths.size()
if (digits.size() == paths.size()) {
result.push_back(paths);
return;
}
// 遍历
for (int i = 0; i < digit_to_char[digits[Rindex]].size(); ++i) {
// 更新paths
paths += digit_to_char[digits[Rindex]][i];
// 递归
backtracking(digits, Rindex + 1);
// 回溯
paths.pop_back();
}
}
vector<string> letterCombinations(string digits) {
if (digits.size() == 0) return result;
backtracking(digits, 0);
return result;
}
};
代码(四刷自解 2024年5月22日)
class Solution {
public:
unordered_map<char,string> nums_to_letter{{'2', "abc"}, {'3', "def"},
{'4', "ghi"}, {'5', "jkl"}, {'6', "mno"},
{'7', "pqrs"},{'8', "tuv"}, {'9', "wxyz"}};
string path;
vector<string> res;
void backtracking(string digits, int index) {
if (index > digits.size()) return;
if (path.size() == digits.size()) {
res.push_back(path);
return;
}
for (int i = 0; i < nums_to_letter[digits[index]].size(); i++) {
path += nums_to_letter[digits[index]][i];
cout<<path<<endl;
backtracking(digits, index + 1);
path.pop_back();
}
}
vector<string> letterCombinations(string digits) {
path = {};
res.clear();
if (digits == "") return res;
backtracking(digits, 0);
return res;
}
};