@@ -553,35 +553,44 @@ class Solution {
553553
554554#### C
555555
556- ``` C
557- char *map[] = {"", "", "abc", "def", "ghi",
558- "jkl", "mno", "pqrs", "tuv", "wxyz"};
559-
560- void backtrack(char * d, int i, char * cur, char ** res, int * sz) {
561- if (!d[ i] ) {
562- res[ (* sz)++] = strdup(cur);
563- return;
564- }
565- for (char * p = map[ d[ i] - '0'] ; * p; p++) {
566- cur[ i] = * p;
567- backtrack(d, i + 1, cur, res, sz);
568- }
569- }
556+ ``` c
557+ char * d[] = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
570558
571- char **letterCombinations (char * d, int * sz) {
572- * sz = 0;
573- if (!* d)
574- return NULL;
575- int max = 1, len = strlen(d);
576- for (int i = 0; i < len; i++)
577- max * = (d[ i] == '7' || d[ i] == '9') ? 4 : 3;
578- char ** res = malloc(max * sizeof(char * )), * cur = malloc(len + 1);
579- cur[ len] = '\0';
580- backtrack(d, 0, cur, res, sz);
581- free(cur);
582- return res;
583- }
559+ char** letterCombinations(char* digits, int* returnSize) {
560+ if (!* digits) {
561+ * returnSize = 0;
562+ return NULL;
563+ }
584564
565+ int size = 1;
566+ char** ans = (char**) malloc(sizeof(char*));
567+ ans[0] = strdup("");
568+
569+ for (int x = 0; digits[x]; ++x) {
570+ char* s = d[digits[x] - '2'];
571+ int len = strlen(s);
572+ char** t = (char**) malloc(sizeof(char*) * size * len);
573+ int tSize = 0;
574+
575+ for (int i = 0; i < size; ++i) {
576+ for (int j = 0; j < len; ++j) {
577+ int oldLen = strlen(ans[i]);
578+ char* tmp = (char*) malloc(oldLen + 2);
579+ strcpy (tmp, ans[ i] );
580+ tmp[ oldLen] = s[ j] ;
581+ tmp[ oldLen + 1] = '\0';
582+ t[ tSize++] = tmp;
583+ }
584+ free(ans[ i] );
585+ }
586+ free(ans);
587+ ans = t;
588+ size = tSize;
589+ }
590+
591+ *returnSize = size;
592+ return ans;
593+ }
585594```
586595
587596<!-- tabs: end -->
0 commit comments