[leetcode] 17. 电话号码的字母组合
排列题目,很容易想到回溯。下面是ac代码。
class Solution {
private:
vector<string> vstrs = {"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
public:
void backtrack(vector<string>& ans, int idx, const string& s, string& str) {
if(idx == s.size()){
ans.push_back(str);
str = ""; // 1
return;
}
for(int i=0; i<vstrs[s[idx]-'0'].size(); ++i) {
string bak = str;
str += vstrs[s[idx]-'0'][i];
backtrack(ans, idx+1, s, str);
str = bak; // 2
}
}
vector<string> letterCombinations(string digits) {
vector<string> ans;
if(!digits.empty()){
string str;
backtrack(ans, 0, digits, str);
}
return ans;
}
};
和官方题解比,官方的数字字母映射用的unordered_map。
1 处实际上不用把str清空
2 处用push_back pop_back更清楚一点
附官方C++题解
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;
backtrack(combinations, phoneMap, digits, 0, combination);
return combinations;
}
void backtrack(vector<string>& combinations, const unordered_map<char, string>& phoneMap, const string& digits, int index, string& combination) {
if (index == digits.length()) {
combinations.push_back(combination);
} else {
char digit = digits[index];
const string& letters = phoneMap.at(digit);
for (const char& letter: letters) {
combination.push_back(letter);
backtrack(combinations, phoneMap, digits, index + 1, combination);
combination.pop_back();
}
}
}
};