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”].
模拟,用递归就ok啦
class Solution {
public:
char change(char c, int a)
{
char n[300][300];
n['2'][0] = '3',n['2'][1] = 'a',n['2'][2] = 'b',n['2'][3] = 'c';
n['3'][0] = '3',n['3'][1] = 'd',n['3'][2] = 'e',n['3'][3] = 'f';
n['4'][0] = '3',n['4'][1] = 'g',n['4'][2] = 'h',n['4'][3] = 'i';
n['5'][0] = '3',n['5'][1] = 'j',n['5'][2] = 'k',n['5'][3] = 'l';
n['6'][0] = '3',n['6'][1] = 'm',n['6'][2] = 'n',n['6'][3] = 'o';
n['7'][0] = '4',n['7'][1] = 'p',n['7'][2] = 'q',n['7'][3] = 'r',n['7'][4] = 's';
n['8'][0] = '3',n['8'][1] = 't',n['8'][2] = 'u',n['8'][3] = 'v';
n['9'][0] = '4',n['9'][1] = 'w',n['9'][2] = 'x',n['9'][3] = 'y',n['9'][4] = 'z';
n['#'][0] = '2',n['#'][1] = 'h',n['#'][2] = 'X';
return n[c][a];
}
vector<string> s;
int len;
void getit(string d, int n, string ss)
{
int y = change(d[n - 1], 0) - '0';
if(n == len)
{
for(int i = 1; i <= y; ++ i)
s.push_back(ss + change(d[n - 1], i));
return ;
}
for(int i = 1; i <= y; ++ i)
getit(d, n + 1, ss + change(d[n - 1], i));
return ;
}
vector<string> letterCombinations(string digits) {
len = digits.size();
if(len < 1) return s;
getit(digits, 1, "");
return s;
}
};