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
Code:
class Solution { public: int len; void combine(int n, string s, vector<string> &res){ if(n==len) res.push_back(s); else for(int i=0;i<res[n].size();i++) combine(n+1,s+res[n][i],res); } vector<string> letterCombinations(string digits) { vector<string> res; len=digits.size(); string letters[] = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; for(int i=0;i<len;i++){ if(digits[i]!='0'&&digits[i]!='1') res.push_back(letters[digits[i]-'2']); } combine(0,"",res); res.erase(res.begin(),res.begin()+len); return res; } };
Another answer:
class Solution { public: vector<string> letterCombinations(string digits) { const string letters[] = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; vector<string> ret(1, ""); for (int i = 0; i < digits.size(); ++i) { for (int j = ret.size() - 1; j >= 0; --j) { const string &s = letters[digits[i] - '2']; for (int k = s.size() - 1; k >= 0; --k) { if (k) ret.push_back(ret[j] + s[k]); else ret[j] += s[k]; } } } return ret; } };