# 17. Letter Combinations of a Phone Number 电话号码的字母组合

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.

### 解法1

``````class Solution {
public:
vector<string> letterCombinations(string digits) {
vector<string> res;
if (digits.empty()) return res;
string dict[] = {"abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
letterCombinationsDFS(digits,dict,0,"",res);
return res;
}
void letterCombinationsDFS(string digits,string dict[],int level,string out,vector<string>& res){
if (level==digits.size()) res.push_back(out);
else {
//找到当前的数字(2~9)对应的stirng("abc"~"wxyz")
string str = dict[digits[level]-'2'];
for (int i = 0;i < str.size();i++)
{
out.push_back(str[i]);
letterCombinationsDFS(digits,dict,level+1,out,res);
out.pop_back();
}
}
}
};
``````

### 解法2

``````class Solution {
public:
vector<string> letterCombinations(string digits) {
vector<string> res;
if (digits.empty()) return res;
string dict[] = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
res.push_back("");
for (int i=0;i<digits.size();i++)
{
int n = res.size();
string str = dict[digits[i]-'2'];
for (int j = 0; j < n; j++)
{
string tmp = res.front();
res.erase(res.begin());
for (int k = 0;k<str.size();k++)
{
res.push_back(tmp+str[k]);
}
}
}
return res;
}
};
``````