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.
T:
Use a vector to store previously generated combinations. For a new digit, append each of its characters to each of the previous combination.
A:
class Solution {
public:
vector< string > letterCombinations(string digits) {
string charmap[10] = {"0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
vector< string > ret;
ret.push_back("");
for(int i=0; i < digits.size(); i++) {
string str = charmap[digits[i] - '0'];
vector< string > tmp;
for(int j=0; j < str.size(); j++) {
for(int k=0; k < ret.size(); k++) {
tmp.push_back(ret[k]+str[j]);
}
}
ret = tmp;
}
return ret;
}
};
No comments:
Post a Comment