这次的都不是我写的,感觉有点烦,就没写,下次还是会自己写一遍。C版本的比较麻烦,C++的简洁易懂,推荐大家都看下C++的。
C版本
char** letterCombinations(char* digits, int* returnSize) {
char *numLetter[10] ={
"",
"",
"abc",
"def",
"ghi",
"jkl",
"mno",
"pqrs",
"tuv",
"wxyz"
};
int letterLengh[10] = {
0,0,3,3,3,3,3,4,3,4
};
int strNum = 1;
char **letterResult;
int numTemp[8] = {0};
int n = 0,i,j,k;
int den = 0,col = 0;
char digitsTemp = 0;
while(*digits != '\0'){
numTemp[n] = *digits - '0';
strNum *= letterLengh[numTemp[n++]];
digits++;
}
if(strNum == 1){
* returnSize = 0;
return NULL;
}
*returnSize = strNum;
letterResult = malloc(sizeof(char *) * strNum);
for(i = 0; i < strNum; i++){
letterResult[i] = malloc(sizeof(char)*(n+1));
//memset(letterResult[i],0,n+1);
}
den = strNum;
for(i = 0;i <= n; i++){
if(letterLengh[numTemp[i]] > 0)
den /= letterLengh[numTemp[i]];
for(j = 0; j < strNum;j++){
if(letterLengh[numTemp[i]] > 0)
k = j / den % letterLengh[numTemp[i]];
if(i == n){
letterResult[j][col] = '\0';
}
else letterResult[j][col] = numLetter[numTemp[i]][k];
}
col++;
}
return letterResult;
}
C++版本
class Solution {
public:
vector<string> letterCombinations(string digits) {
if (digits.empty()) return {};
vector<string> res{""};
string dict[] = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
for (int i = 0; i < digits.size(); ++i) {
vector<string> t;
string str = dict[digits[i] - '0'];
for (int j = 0; j < str.size(); ++j) {
for (string s : res) t.push_back(s + str[j]);
}
res = t;
}
return res;
}
};
用迭代Iterative来解,在遍历digits中所有的数字时,我们先建立一个临时的字符串数组t,然后跟上面解法的操作一样,通过数字到dict中取出字符串str,然后遍历取出字符串中的所有字符,再遍历当前结果res中的每一个字符串,将字符加到后面,并加入到临时字符串数组t中。取出的字符串str遍历完成后,将临时字符串数组赋值给结果res。