Skip to content

Commit d1aef63

Browse files
authored
Update README.md
1 parent aec2dea commit d1aef63

File tree

1 file changed

+36
-27
lines changed
  • solution/0000-0099/0017.Letter Combinations of a Phone Number

1 file changed

+36
-27
lines changed

solution/0000-0099/0017.Letter Combinations of a Phone Number/README.md

Lines changed: 36 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -557,35 +557,44 @@ class Solution {
557557

558558
#### C
559559

560-
```C
561-
char *map[] = {"", "", "abc", "def", "ghi",
562-
"jkl", "mno", "pqrs", "tuv", "wxyz"};
563-
564-
void backtrack(char *d, int i, char *cur, char **res, int *sz) {
565-
if (!d[i]) {
566-
res[(*sz)++] = strdup(cur);
567-
return;
568-
}
569-
for (char *p = map[d[i] - '0']; *p; p++) {
570-
cur[i] = *p;
571-
backtrack(d, i + 1, cur, res, sz);
572-
}
573-
}
560+
```c
561+
char* d[] = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
574562

575-
char **letterCombinations(char *d, int *sz) {
576-
*sz = 0;
577-
if (!*d)
578-
return NULL;
579-
int max = 1, len = strlen(d);
580-
for (int i = 0; i < len; i++)
581-
max *= (d[i] == '7' || d[i] == '9') ? 4 : 3;
582-
char **res = malloc(max * sizeof(char *)), *cur = malloc(len + 1);
583-
cur[len] = '\0';
584-
backtrack(d, 0, cur, res, sz);
585-
free(cur);
586-
return res;
587-
}
563+
char** letterCombinations(char* digits, int* returnSize) {
564+
if (!*digits) {
565+
*returnSize = 0;
566+
return NULL;
567+
}
588568

569+
int size = 1;
570+
char** ans = (char**) malloc(sizeof(char*));
571+
ans[0] = strdup("");
572+
573+
for (int x = 0; digits[x]; ++x) {
574+
char* s = d[digits[x] - '2'];
575+
int len = strlen(s);
576+
char** t = (char**) malloc(sizeof(char*) * size * len);
577+
int tSize = 0;
578+
579+
for (int i = 0; i < size; ++i) {
580+
for (int j = 0; j < len; ++j) {
581+
int oldLen = strlen(ans[i]);
582+
char* tmp = (char*) malloc(oldLen + 2);
583+
strcpy(tmp, ans[i]);
584+
tmp[oldLen] = s[j];
585+
tmp[oldLen + 1] = '\0';
586+
t[tSize++] = tmp;
587+
}
588+
free(ans[i]);
589+
}
590+
free(ans);
591+
ans = t;
592+
size = tSize;
593+
}
594+
595+
*returnSize = size;
596+
return ans;
597+
}
589598
```
590599

591600
<!-- tabs:end -->

0 commit comments

Comments
 (0)