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"].思路,采用递归法,或者循环。
class Solution {
public:
vector<string> two(vector<string> &a, const string& b)
{
vector<string> result;
if(a.size() == 0)
{
for(int i = 0; i < b.size(); i++){
result.push_back(string(1, b[i]));
}
}
for(int i = 0; i < b.size() ; i++)
{
for(int j = 0; j < a.size(); j++)
{
result.push_back(a[j] + string(1,b[i]));
}
}
return result;
}
vector<string> letterCombinations(string digits) {
string telephone[] = {" ", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
vector<string> before;
for(int i = 0 ; i < digits.size(); i++)
{
if(digits[i] >= '0' && digits[i] <= '9')
{
int digit = digits[i] - '0';
before = two(before, telephone[digit]);
}
}
return before;
}
};