Skip to content

Instantly share code, notes, and snippets.

@safeng
Created November 17, 2013 18:35
Show Gist options
  • Save safeng/7516540 to your computer and use it in GitHub Desktop.
Save safeng/7516540 to your computer and use it in GitHub Desktop.
Letter Combinations of a Phone Number Given a digit string, return all possible letter combinations that the number could represent.
class Solution {
public:
void _lComb(int idx, int idxStr, const string & digits, string & str, vector<string> & res)
{
static string dMap[10] = {" ","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
if(idx == digits.length())
{
res.push_back(str);
}else
{
int d = digits[idx] - '0';
if(d != 1)
{
string comb = dMap[d];
for(int i = 0; i<(int)comb.length(); ++i)
{
str[idxStr] = comb[i];
_lComb(idx+1, idxStr+1, digits, str, res);
}
}else
{
_lComb(idx+1, idxStr, digits, str, res);
}
}
}
vector<string> letterCombinations(string digits) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
string str(digits.length(),'\0');
vector<string> res;
_lComb(0, 0, digits, str, res);
return res;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment