Created
November 17, 2013 18:35
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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