1 题目
Given a string containing digits from 2-9
inclusive, 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. Note that 1 does not map to any letters.
Example:
Input: "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.
2 尝试解
class Solution {
public:
vector<string> letterCombinations(string digits) {
map<char,string> dict {{'2',"abc"},{'3',"def"},{'4',"ghi"},{'5',"jkl"},{'6',"mno"},{'7',"pqrs"},{'8',"tuv"},{'9',"wxyz"}};
vector<string> result;
if(digits.size() == 0) return result;
string temp = "";
CombineLetters(digits,0,temp,result,dict);
return result;
}
void CombineLetters(string &digits,int index,string &temp,vector<string> &result,map<char,string> &dict){
if(index == digits.size()){
result.push_back(temp);
return;
}
for(int i = 0; i < dict[digits[index]].size(); i++){
temp = temp + dict[digits[index]][i];
CombineLetters(digits,index+1,temp,result,dict);
temp.pop_back();
}
}
};
3 标准解
class Solution {
public:
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;
}
};