leetcode17
给定一个仅包含数字 2-9
的字符串,返回所有它能表示的字母组合。答案可以按 任意顺序 返回。
给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。
示例 1:
输入:digits = "23" 输出:["ad","ae","af","bd","be","bf","cd","ce","cf"]
循环无法解决四个数字及以上的情况,需要递归。因为0和1不对应字母,我们先删除字符串中的0和1。
写递归代码不需要细想,只需要明确:1.何时终止递归 return 2.递归下一层与当前层的关系。搞清楚这两点,我们只需要看一条树枝就够了。
对于本题:
1.当指针index走到尽头时,递归终结,储存result。
2.下一层会增加一个字母,这个字母来源于phoneMap中的一个
class Solution {
public:
map<char, string> phoneMap = {
{'2', "abc"},
{'3', "def"},
{'4', "ghi"},
{'5', "jkl"},
{'6', "mno"},
{'7', "pqrs"},
{'8', "tuv"},
{'9', "wxyz"}
};
vector<string> letterCombinations(string digits) {
for (int i = 0; i < digits.length(); i++) {
if (digits[i] == '0' || digits[i] == '1') {
digits.erase(i, 1);
}
}
if (digits == "") {
return {};
}
vector<string> result;
int index = 0;
string temp="";
addletter( digits,index,temp,result );
return result;
}
private:
void addletter(string digits, int index, string temp, vector<string>& result) {
if (index == digits.length()) {
result.push_back(temp);
return;
}
string str = phoneMap[digits[index]];
for (auto element : str) {
addletter(digits, index+1, temp + element, result);
}
}
};
int main()
{
Solution solution;
string digits = "5678";
vector<string> res = solution.letterCombinations(digits);
for (auto element : res) {
cout << element << " ";
}
return 0;
}