- Letter Combinations of a Phone Number
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.
题目解析:
题目就是字母排列组合,大家学过排列组合的想必都知道,看到题目直观感受就是暴力组合。
代码:
class Solution {
public:
vector<string> letterCombinations(string digits) {
vector<string> res,tempRes;//返回结果
int length = digits.size();//输入长度
if(length == 0)
{
return vector<string>();//只能返回[],不能返回"",不然无法通过测试
}
res.push_back("");//初始化
string tempStr;
map<char, vector<char>> dic;//输入号码字符集
dic.insert(pair<char, vector<char>>('1', {}));
dic.insert(pair<char, vector<char>>('2', {'a','b','c'}));
dic.insert(pair<char, vector<char>>('3', {'d','e','f'}));
dic.insert(pair<char, vector<char>>('4', {'g','h','i'}));
dic.insert(pair<char, vector<char>>('5', {'j','k','l'}));
dic.insert(pair<char, vector<char>>('6', {'m','n','o'}));
dic.insert(pair<char, vector<char>>('7', {'p','q','r','s'}));
dic.insert(pair<char, vector<char>>('8', {'t','u','v'}));
dic.insert(pair<char, vector<char>>('9', {'w','x','y','z'}));
for(int i=0;i<length;i++)
{
int resLen = res.size();
tempRes.clear();//每次执行完,必须清零
vector<char> charList = dic[digits[i]];
for(int j=0;j<resLen;j++)
{
tempStr = res[j];
for(int k=0;k<charList.size();k++)
{
tempRes.push_back(tempStr + charList[k]);
}
}
res = tempRes;//相当于递归
}
return res;
}
};
特别说明:
for循环中采用了tempRes来获取最终的结果,相当于遍历出所有结果,例如:我们代码中res初始化为{""};第一次遍历的时候tempRes即为digits中第一个数值代表的字母集合,如果第一个数值是2的话,此时tempRes即为{‘a’,‘b’,‘c’},赋值给res;然后进行第二次遍历,获取第二个数值代表的字母集合,重新push到tempRes中,所以每次遍历tempRes必须清零,tempRes.clear()。
代码性能:
总结:最近忙新接手新项目,在新环境接受新挑战,写博客的频率,有所降低,一时反应偏慢,还得坚持,逆水行舟,不进则退,继续加油,坚持写博;上述代码属于暴力破解,递归思想,使用内存空间较多,不建议使用,大家有好的方法,欢迎给个链接。谢谢大家。