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