17 Letter Combinations of a Phone Number
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"].
Solution
class Solution {
public:
vector<string> letterCombinations(string digits) {
vector<string> letter(8, "");
letter[0] = "abc";
letter[1] = "def";
letter[2] = "ghi";
letter[3] = "jkl";
letter[4] = "mno";
letter[5] = "pqrs";
letter[6] = "tuv";
letter[7] = "wxyz";
vector<string> res1;
if ( digits.size() == 0 ) return res1;
res1.push_back("");
for ( int i = 0; i <= digits.size()-1; i++ ) {
vector<string> res2;
int nres = res1.size();
int digit = atoi(digits.substr(i, 1).c_str())-2;
for ( int j = 0; j <= nres-1; j++ ) {
string tmp = res1[j];
for ( int k = 0; k <= letter[digit].size()-1; k++ ) res2.push_back(tmp + letter[digit][k]);
}
res1 = res2;
}
return res1;
}
};