1.题目
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"].
2.思路
记录下每个数字对应的字符串,然后对于每个加进来的数字扩充现有的结果,实现起来也很简单,可以用vector中的swap方法替换每一轮的结果
3.代码
vector<string> letterCombinations(string digits) {
vector<string> result;
if(digits.empty()) return vector<string>();
static const vector<string> v = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
result.push_back(""); // add a seed for the initial case
for(int i = 0 ; i < digits.size(); ++i) {
int num = digits[i]-'0';
if(num < 0 || num > 9) break;
const string& candidate = v[num];
if(candidate.empty()) continue;
vector<string> tmp;
for(int j = 0 ; j < candidate.size() ; ++j) {
for(int k = 0 ; k < result.size() ; ++k) {
tmp.push_back(result[k] + candidate[j]);
}
}
result.swap(tmp);
}
return result;