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.
题意:根据手机数字的输入转换为字母。
思路:递归直接实现。
class Solution {
public:
vector<string> letterCombinations(string digits) {
vector<string> res;
if (digits.empty())
return res;
unordered_map<char, string> mymap = {
{ '2', "abc" },
{ '3', "def" },
{ '4', "ghi" },
{ '5', "jkl" },
{ '6', "mno" },
{ '7', "pqrs" },
{ '8', "tuv" },
{ '9', "wxyz" }
};
recursion("", digits.size(), digits, mymap, res);
return res;
}
void recursion(string s, int level, string digits, unordered_map<char, string> mymap, vector<string>& res){
if (level == 0){
res.push_back(s);
return;
}
else{
char ch = digits[digits.size() - level];
for (int i = 0; i < mymap[ch].size(); i++){
string str = s + mymap[ch][i];
recursion(str, level-1, digits, mymap, res);
}
}
}
};