17. 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"].
类似于手机输入法,输入一串数字,列出所有可能的字母情况
思路:
感觉这题也没什么方法啥的,完全就是考验STL特别是MAP的使用,还有一些逻辑能力?我这完全暴力的方法居然就是最优了,当然大家也都是这样的
vector<string> letterCombinations(string digits) {
int sz = digits.size(), tvsz;
if (sz == 0)
return vector<string>();
map<char, vector<char>> dic;
vector<char> tv;
vector<string> res, tres;
res.push_back(string());
string ts;
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 < sz; ++i) {
int ressz = res.size();
tres.clear();
tv = dic[digits[i]];
tvsz = tv.size();
for (int j = 0; j < ressz; ++j) {
ts = res[j];
for (int z = 0; z < tvsz; ++z) {
tres.push_back(ts + tv[z]);
}
}
res = tres;
}
return res;
}