class Solution {
public:
vector<string> res;
vector<string> letterCombinations(string digits) {
string mapping[] = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
res.clear();
string s;
letterCombinationsRe(digits, mapping, s);
return res;
}
void letterCombinationsRe(const string &digits, string mapping[], string &s)
{
if (s.size() == digits.size())
{
res.push_back(s);
return;
}
string &letters = mapping[digits[s.size()]-'2'];
for (int i = 0; i < letters.size(); ++i)
{
s.push_back(letters[i]);
letterCombinationsRe(digits, mapping, s);
s.pop_back();
}
}
};
class Solution {
public:
unordered_map<char, string> dig2char;
Solution()
{
dig2char['2'] = "abc";
dig2char['3'] = "def";
dig2char['4'] = "ghi";
dig2char['5'] = "jkl";
dig2char['6'] = "mno";
dig2char['7'] = "pqrs";
dig2char['8'] = "tuv";
dig2char['9'] = "wxyz";
}
vector<string> letterCombinations(string digits) {
vector<string> result;
result.push_back("");
if ( digits.size() == 0 )
{
return result;
}
int n=digits.length();
for(int i=0;i<n;i++){
vector<string> tmp;
for(int j=0;j<dig2char[digits[i]].length();j++){
for(int k=0;k<result.size();k++){
tmp.push_back(result[k]+dig2char[digits[i]][j]);
}
}
result=tmp;
}
return result;
}
vector<string> letterCombinations2(string digits) {
vector<string> result;
if ( digits.size() == 0 )
{
result.push_back("");
return result;
}
vector<string> temp = letterCombinations(digits.substr(1));
for(int j = 0; j < dig2char[digits[0]].size(); j ++)
for(int t = 0; t < temp.size(); t ++ )
result.push_back(dig2char[digits[0]][j] + temp[t]);
return result;
}
};
No comments:
Post a Comment