题目:
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.
Solution:
利用树的遍历算法,递归叠加。
vector<string> letterCombinations(string digits)
{
vector<string> result;
vector<string> t_result;
string temp = "";
if(digits.size() == 0)
return result;
vector<char> tra_letters = getLetter(digits[0]);
if(digits.size() == 1)
{
for(int i =0;i<tra_letters.size();i++)
{
temp = tra_letters[i];
result.push_back(temp);
}
return result;
}
for(int i =0 ;i<tra_letters.size();i++)
{
t_result = letterCombinations(digits.substr(1));
for(int j=0;j<t_result.size();j++)
{
temp = tra_letters[i] + t_result[j];
result.push_back(temp);
}
}
return result;
}
vector<char> getLetter(char str)
{
vector<char> letters;
switch(str)
{
case '2':
{
letters.push_back('a');
letters.push_back('b');
letters.push_back('c');
break;
}
case '3':
{
letters.push_back('d');
letters.push_back('e');
letters.push_back('f');
break;
}
case '4':
{
letters.push_back('g');
letters.push_back('h');
letters.push_back('i');
break;
}
case '5':
{
letters.push_back('j');
letters.push_back('k');
letters.push_back('l');
break;
}
case '6':
{
letters.push_back('m');
letters.push_back('n');
letters.push_back('o');
break;
}
case '7':
{
letters.push_back('p');
letters.push_back('q');
letters.push_back('r');
letters.push_back('s');
break;
}
case '8':
{
letters.push_back('t');
letters.push_back('u');
letters.push_back('v');
break;
}
case '9':
{
letters.push_back('w');
letters.push_back('x');
letters.push_back('y');
letters.push_back('z');
break;
}
default:return letters;
}
return letters;
}