问题
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.
代码
void myletterCombinations(const char *s , vector<string> &v , string currentString)
{
if (!s) {
return;
}
if (*s != '\0') {
char testA[12];
char a = ('a' + ((*s-'2') * 3));
//sprintf(testA, "%c" , a + 4);
/* get next */
switch (*s) {
case '9':
myletterCombinations(s + 1, v, currentString + string("w"));
myletterCombinations(s + 1, v, currentString + string("x"));
myletterCombinations(s + 1, v, currentString + string("y"));
myletterCombinations(s + 1, v, currentString + string("z"));
break;
case '8':
myletterCombinations(s + 1, v, currentString + string("t"));
myletterCombinations(s + 1, v, currentString + string("u"));
myletterCombinations(s + 1, v, currentString + string("v"));
break;
case '7':
myletterCombinations(s + 1, v, currentString + string("p"));
myletterCombinations(s + 1, v, currentString + string("q"));
myletterCombinations(s + 1, v, currentString + string("r"));
myletterCombinations(s + 1, v, currentString + string("s"));
break;
case '6':
case '5':
case '4':
case '3':
case '2':
{
sprintf(testA, "%c" , a);
myletterCombinations(s + 1, v, currentString + string(testA));
sprintf(testA, "%c" , a+1);
myletterCombinations(s + 1, v, currentString + string(testA));
sprintf(testA, "%c" , a +2);
myletterCombinations(s + 1, v, currentString + string(testA));
break;
}
default:
myletterCombinations(s + 1, v, currentString);
break;
}
}
else{
v.push_back(currentString);
}
}
class Solution {
public:
vector<string> letterCombinations(string digits) {
vector<string> ss;
myletterCombinations(digits.c_str(), ss, string(""));
return ss;
}
};
分析
这里注意不仅仅是 9 有四个字符,7也是,我开始没注意。 2-6 是没问题的,使用通用的算法计算就可以了。 7,9 不行,8自然在中间也不能独自计算。
递归之就行了。跳过了 0 , 1, #,* 等无意义的输入,我没有试过假设不处理这几个字符是否会拒绝我的代码。
总结
递归各种组合。递归之前想好递归的停止条件是啥。