17.Letter Combinations of a Phone Number
Letter Combinations of a Phone Number Total Accepted: 34954 Total Submissions: 134310 Question Solution
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.
Show Tags Have you met this question in a real interview? Yes No
思路:回溯法。既不是子集树,也不是排列树。普通回溯。
class Solution { public:
void solve(string &digits,int pos,unordered_map<char,string> &my_map,vector<string> &res,string &one_res){
if(pos>=digits.size()){
res.push_back(one_res);
return;
}else{
string tem_string=my_map[digits[pos]];
for(int i=0;i<tem_string.size();++i){
one_res+=tem_string[i];
solve(digits,pos+1,my_map,res,one_res);
one_res.pop_back();//C++11中的string还是有这个接口的
}
}
}
vector<string> letterCombinations(string digits) {
vector<string> res;
if(digits=="") return res;//简单判错
unordered_map<char,string> my_map={{'2',"abc"},{'3',"def"},{'4',"ghi"},{'5',"jkl"},{'6',"mno"},{'7',"pqrs"},{'8',"tuv"},{'9',"wxyz"}};
string one_res;
solve(digits,0,my_map,res,one_res);
return res;
}
};