上一题:LeetCode第16题: threeSumClosest(C语言)
思路:如果第一个输入的数字是1,其对应的字母为‘abc’,由于1对应的字母有三个,则在输出结果中分别添加三个字符串,每个字符串分别为‘a’,‘b’,‘c’;
如果第二个输入的数字是7,其对应的字母为‘pqrs’,由于7对应的字母有四个,所以输出的结果数量有排列组合可知:3乘以4=12个结果,所以需要把上一步的结果复制成12份,然后将本次的‘pqrs’均匀填入12份结果中。
char** letterCombinations(char* digits, int* returnSize) {
char *base[10] = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
int length = strlen(digits);
if(length == 0){
*returnSize = 0;
return '\0';
}
int max_result_count = 1;
for(int i = 0; i < length; i++){
max_result_count *= 4;
}
char **result = (char *)malloc(max_result_count * sizeof(char *));
int real_count = 0;
int letters_count = 0;
for(int i = 0; i < length; i++){
int num = digits[i] - 48;
char *letters = base[num];
if(num == 7 || num == 9){
letters_count = 4;
}
else{
letters_count = 3;
}
if(real_count == 0){
for(int j = 0; j < letters_count; j++){
char *new_result = (char *)malloc((length + 1) * sizeof(char));
new_result[0] = letters[j];
result[real_count++] = new_result;
}
}
else{
int last_result_count = real_count;
for(int j = last_result_count; j < last_result_count * letters_count; j++){
int origin_index = j % last_result_count;
char *origin_result = result[origin_index];
char *new_result = (char *)malloc((length + 1) * sizeof(char));
for(int k = 0; k < i; k++){
new_result[k] = origin_result[k];
}
result[real_count++] = new_result;
}
for(int j = 0; j < real_count; j++){
char *origin_result = result[j];
int index = j / last_result_count;
origin_result[i] = letters[index];
}
}
}
for(int j = 0; j < real_count; j++){
char *sub_result = result[j];
sub_result[length] = '\0';
}
*returnSize = real_count;
return result;
}
本系列文章,旨在打造LeetCode题目解题方法,帮助和引导同学们开阔学习算法思路,由于个人能力和精力的局限性,也会参考其他网站的代码和思路,如有侵权,请联系本人删除。