问题:链接
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.
DFS
参考:http://www.cnblogs.com/Rosanna/p/3416949.html
代码:
class Solution {
public:
vector<string> letterCombinations(string digits) {
string strlist[8] = {"abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
string result = "";
m_digits = digits;
if(digits == "")
{
re_str.push_back("");
return re_str;
}
if(digits.size() == 0)
return re_str;
print(result, 0, strlist);
return re_str;
}
void print(string result, int i, string strlist[])
{
int num = m_digits[i] - '0';
if(i < m_digits.size())
{
for(int j = 0; j < strlist[num-2].size(); ++j)
{
print(result + strlist[num-2][j], i+1, strlist);
}
}
else
{
re_str.push_back(result);
}
}
private:
vector<string> re_str;
string m_digits;
};