今天刷的第一题难度适中,下面就和大家分享一下经验吧!
题目如下:
Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent.
A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.
Example:
Input: "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
Note:
Although the above answer is in lexicographical order, your answer could be in any order you want.
题意分析:
给定一个包含数字2-9的字符串,每个数字都按照手机键盘那样对应多个字母,请找到数字间对应字母的组合并返回。
方法一(递归法)
将本题转成树形问题来求解(如下图),然后采用递归的思路去层层累加,即s(digits[n]) = letter(digits[0]) + s(digits[1,....,n-1])。
解题代码如下:
class Solution{
private:
const string digitsMap[10] = {
" ",
"",
"abc",
"def",
"ghi",
"jkl",
"mno",
"pqrs",
"tuv",
"wxyz"
};
vector<string> res;
void FindCombinations(const string &digits, int index, const string &s){
if (index == digits.size())
{ res.push_back(s);
return;}
char digit = digits[index];
string letters = digitsMap[digit - '0'];
//对每个字母都调用递归函数,直到满足递归终止条件if (index == digits.size()),然后保存每条递归路径获得的字符串即图中树的每条分支
for (int i = 0; i < letters.size(); i++) {
FindCombinations(digits, index+1, s + letters[i]);
}
return;
}
public:
vector<string> letterCombinations(string digits) {
res.clear();
//如果传入的digits字符串为空,则返回空res
if(digits.size() == 0) return res;
FindCombinations(digits, 0, "");
return res;
}
};
提交后的结果如下:
方法二(枚举法)
对于后遍历到的每一个输入数字,将其对应的每一个字符,分别加入之前已组合好并存入res中的每一个字符串。该方法共需三层for循环。
解题代码如下:
class Solution{
public:
vector<string> letterCombinations(string digits){
vector<string> res;
res.clear();
if(digits.size() == 0) return res;
res.push_back("");
string digitsMap[10] = {
" ",
"",
"abc",
"def",
"ghi",
"jkl",
"mno",
"pqrs",
"tuv",
"wxyz"
};
//遍历数字字符串digits
for (int i = 0; i < digits.size(); i++) {
int size = res.size();
//遍历上一轮加入res中的结果,挨个与新添字符进行组合同时也被挨个删除
for (int j = 0; j < size; j++) {
string cur = res[0];
res.erase(res.begin());
//本轮加入res中的结果
for (int k = 0; k < digitsMap[digits[i]-'0'].size(); k++) {
res.push_back(cur + digitsMap[digits[i]-'0'][k]);
}
}
}
return res;
}
};
提交后的结果如下:
日积月累,与君共进,增增小结,未完待续。