Given a digit string, 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.
Input:Digit string "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.
[Analysis]
使用map进行数字到字符串的映射,再递归。
[Solution]
class Solution {
public:
// combination letters
vector<string> combination(string digits, map<char, string> &letterTable){
vector<string> res;
// empty string
if(digits.length() <= 0){
res.push_back("");
return res;
}
// one digit string
else if(digits.length() == 1){
char ch = digits[0];
if(ch >= '0' && ch <= '9'){
string letters = letterTable[ch];
for(int i = 0; i < letters.length(); ++i){
res.push_back(letters.substr(i, 1));
}
}
}
else{
char ch = digits[0];
if(ch >= '0' && ch <= '9'){
string letters = letterTable[ch];
vector<string> r = combination(digits.substr(1, digits.length()-1), letterTable);
for(int i = 0; i < letters.length(); ++i){
for(int j = 0; j < r.size(); ++j){
res.push_back(letters.substr(i, 1) + r[j]);
}
}
}
}
return res;
}
// letter combinations
vector<string> letterCombinations(string digits) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
// letter table
map<char, string> letterTable;
letterTable['0'] = " ";
letterTable['1'] = "";
letterTable['2'] = "abc";
letterTable['3'] = "def";
letterTable['4'] = "ghi";
letterTable['5'] = "jkl";
letterTable['6'] = "mno";
letterTable['7'] = "pqrs";
letterTable['8'] = "tuv";
letterTable['9'] = "wxyz";
return combination(digits, letterTable);
}
};
说明:版权所有,转载请注明出处。 Coder007的博客