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.

Although the above answer is in lexicographical order, your answer could be in any order you want.
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.
string keypad[8] = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
void generate(string digits, string result, int i,vector<string> &ans)
{
if(i >= digits.size())
{
ans.push_back(result);
return;
}
if(digits[i] <= '1' || digits[i] > '9')
{
generate(digits, result, i +1, ans);
}
else
{
string t = keypad[digits[i] - '2'];
for(int r = 0; r < t.size(); r++)
{
generate(digits, result + t[r], i+1, ans);
}
}
}
vector<string> letterCombinations(string digits) {
string result = "";
vector<string> ans;
generate(digits, result, 0, ans);
return ans;
}
No comments:
Post a Comment