Skip to content

Commit 0c4216d

Browse files
authored
Update Solution.c
1 parent 39fa66c commit 0c4216d

File tree

1 file changed

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

1 file changed

+32
-22
lines changed
Lines changed: 32 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,37 @@
1-
char* map[] = {"", "", "abc", "def", "ghi",
2-
"jkl", "mno", "pqrs", "tuv", "wxyz"};
1+
char* d[] = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
32

4-
void backtrack(char* d, int i, char* cur, char** res, int* sz) {
5-
if (!d[i]) {
6-
res[(*sz)++] = strdup(cur);
7-
return;
3+
char** letterCombinations(char* digits, int* returnSize) {
4+
if (!*digits) {
5+
*returnSize = 0;
6+
return NULL;
87
}
9-
for (char* p = map[d[i] - '0']; *p; p++) {
10-
cur[i] = *p;
11-
backtrack(d, i + 1, cur, res, sz);
8+
9+
int size = 1;
10+
char** ans = (char**) malloc(sizeof(char*));
11+
ans[0] = strdup("");
12+
13+
for (int x = 0; digits[x]; ++x) {
14+
char* s = d[digits[x] - '2'];
15+
int len = strlen(s);
16+
char** t = (char**) malloc(sizeof(char*) * size * len);
17+
int tSize = 0;
18+
19+
for (int i = 0; i < size; ++i) {
20+
for (int j = 0; j < len; ++j) {
21+
int oldLen = strlen(ans[i]);
22+
char* tmp = (char*) malloc(oldLen + 2);
23+
strcpy(tmp, ans[i]);
24+
tmp[oldLen] = s[j];
25+
tmp[oldLen + 1] = '\0';
26+
t[tSize++] = tmp;
27+
}
28+
free(ans[i]);
29+
}
30+
free(ans);
31+
ans = t;
32+
size = tSize;
1233
}
13-
}
1434

15-
char** letterCombinations(char* d, int* sz) {
16-
*sz = 0;
17-
if (!*d)
18-
return NULL;
19-
int max = 1, len = strlen(d);
20-
for (int i = 0; i < len; i++)
21-
max *= (d[i] == '7' || d[i] == '9') ? 4 : 3;
22-
char **res = malloc(max * sizeof(char*)), *cur = malloc(len + 1);
23-
cur[len] = '\0';
24-
backtrack(d, 0, cur, res, sz);
25-
free(cur);
26-
return res;
35+
*returnSize = size;
36+
return ans;
2737
}

0 commit comments

Comments
 (0)