上一題:LeetCode第16題: threeSumClosest(C語(yǔ)言)
思路:如果第一個(gè)輸入的數(shù)字是1羽历,其對(duì)應(yīng)的字母為‘a(chǎn)bc’炼团,由于1對(duì)應(yīng)的字母有三個(gè)褥琐,則在輸出結(jié)果中分別添加三個(gè)字符串,每個(gè)字符串分別為‘a(chǎn)’,‘b’,‘c’;
如果第二個(gè)輸入的數(shù)字是7驱富,其對(duì)應(yīng)的字母為‘pqrs’,由于7對(duì)應(yīng)的字母有四個(gè)匹舞,所以輸出的結(jié)果數(shù)量有排列組合可知:3乘以4=12個(gè)結(jié)果,所以需要把上一步的結(jié)果復(fù)制成12份叫榕,然后將本次的‘pqrs’均勻填入12份結(jié)果中姊舵。
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題目解題方法构资,幫助和引導(dǎo)同學(xué)們開(kāi)闊學(xué)習(xí)算法思路,由于個(gè)人能力和精力的局限性迹淌,也會(huì)參考其他網(wǎng)站的代碼和思路己单,如有侵權(quán),請(qǐng)聯(lián)系本人刪除句携。