题目要求
整体思路
首先建一个长度为10的vecotor,存放与数字相对应的字母
接着根据digits的长度,利用深度优先递归的组成字符串:
当nowIndex小于maxIndex(字符串长度)时,将digits[index]数字对应的所有字母分别加入字符串尾部。
当nowIndex大于maxIndex(字符串长度)时,将组成的字符串放进字符串数组中。
最后返回字符数组
代码
class Solution {
public:
vector<vector<char>> vChar;
vector<string> letterCombinations(string digits)
{
//特殊值判断
if (digits.empty())
{
return {};
}
vectorInit();
vector<string> vStr;
combineStr(0, digits.size() - 1, "", digits, vStr);
return vStr;
}
//初始化字符数组
void vectorInit()
{
vChar.push_back({});
vChar.push_back({});
vChar.push_back({'a','b','c'});
vChar.push_back({'d','e','f'});
vChar.push_back({ 'g','h','i' });
vChar.push_back({ 'j','k','l' });
vChar.push_back({ 'm','n','o' });
vChar.push_back({ 'p','q','r', 's' });
vChar.push_back({ 't','u','v' });
vChar.push_back({ 'w','x','y', 'z' });
}
//递归地组成字符串
void combineStr(int nowIndex, const int maxIndex, string str, const string &digits, vector<string>& v)
{
if (nowIndex > maxIndex)
{
v.push_back(str);
}
else
{
for (auto i : vChar[digits[nowIndex] - '0'])
{
str.push_back(i);
combineStr(nowIndex + 1, maxIndex, str, digits, v);
str.pop_back();
}
}
}
};
学到了什么
1、注意特殊值判断,当字符串为空的时候。(因为这个提交错误一次)