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:
class Solution {
public:
vector<string> letterCombinations(string digits) {
vector<string> res;
if(digits.empty()) return res;
vector<string> dict(10);
dict[2] = "abc";
dict[3] = "def";
dict[4] = "ghi";
dict[5] = "jkl";
dict[6] = "mno";
dict[7] = "pqrs";
dict[8] = "tuv";
dict[9] = "wxyz";
dfs(digits, 0, "", res, dict);
return res;
}
void dfs(string digits, int depth, string str, vector<string> &res, vector<string> dict)
{
if(depth == digits.size())
{
res.push_back(str);
return ;
}
int index = digits[depth] - '0';
for(int i = 0; i < dict[index].size(); ++i)
{
str += dict[index][i];
dfs(digits, depth + 1, str, res, dict);
str.erase(str.end() - 1);
}
}
};