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 .
这道题目非常简单的题目,用递归或者队列非常容易做出结果。
class Solution {
public :
int initDict(vector <vector <string > > & dict){
char str[2 ];
str[1 ] = '\0' ;
for (int i = 2 ;i<=6 ;++i){
for (int j = 0 ;j<=2 ;++j){
str[0 ] = 'a' + (i-2 )*3 +j;
dict[i].push_back(string (str));
}
}
for (int i = 0 ;i <= 3 ;++i){
str[0 ] = 'p' +i;
dict[7 ].push_back(string (str));
}
for (int i = 0 ;i <= 2 ;++i){
str[0 ] = 't' +i;
dict[8 ].push_back(string (str));
}
for (int i = 0 ;i <= 3 ;++i){
str[0 ] = 'w' +i;
dict[9 ].push_back(string (str));
}
return 0 ;
}
vector <string > letterCombinations(string digits) {
int n = digits.size();
queue <string > que;
vector <string > res;
vector <vector <string > > dict(10 ,res);
char str[2 ] = {0 };
initDict(dict);
for (int i = 0 ;i < n;++i ){
if (digits[i]=='0' ||digits[i]=='1' ){
return res;
}
int m = que.size();
if (m == 0 ){
for (int k = 0 ;k<dict[digits[i]-'0' ].size();++k) {
que.push(dict[digits[i]-'0' ][k]);
}
}
for (int j = 1 ;j <= m;++j){
string s;
if (!que.empty()){
s = que.front();
que.pop();
}
for (int k = 0 ;k<dict[digits[i]-'0' ].size();++k) {
que.push(s+dict[digits[i]-'0' ][k]);
}
}
}
while (!que.empty()){
res.push_back(que.front());
que.pop();
}
return res;
}
};