diff --git a/src/22.c b/src/22.c index 4975312..55abfd2 100644 --- a/src/22.c +++ b/src/22.c @@ -4,18 +4,93 @@ #include #include #include -char **generateParenthesis(int n, int *returnSize) + +typedef struct tinode_t { - char **dp = malloc(sizeof(char *) * n); - for (int i = 0; i < n; i++) + char *ans; + struct tinode_t *left; + struct tinode_t *right; +} tinode_t; + +int get_number_of(char *s, char c) +{ + int num = 0; + while (*s != '\0') { - dp[i] = malloc(sizeof(char) * (n + 1)); - memset(dp[i], 0, n + 1); + if (*s == c) + num++; + s++; + } + return num; +} + +void dfs(tinode_t *root, char ***ans, int n, int *retSize) +{ + if (root == NULL) + return; + + // check current number of "(" + int left = get_number_of(root->ans, '('); + // in these time ")" can not greater than "(" + int right = get_number_of(root->ans, ')'); + // we can add a "(" to the ans when "(" less than n + int s_len = strlen(root->ans); + if (left < n) + { + tinode_t *ln = malloc(sizeof(tinode_t)); + ln->ans = malloc(s_len + 2); + strcpy(ln->ans, root->ans); + ln->ans[s_len] = '('; + ln->ans[s_len + 1] = '\0'; + ln->left = NULL; + ln->right = NULL; + root->left = ln; + } + if (right < left) + { + tinode_t *rn = malloc(sizeof(tinode_t)); + rn->ans = malloc(s_len + 2); + strcpy(rn->ans, root->ans); + rn->ans[s_len] = ')'; + rn->ans[s_len + 1] = '\0'; + rn->left = NULL; + rn->right = NULL; + root->right = rn; + } + // endpoint: left + right == 2n + if (right + left == 2 * n) + { + *ans = realloc(*ans, sizeof(char *) * (++(*retSize))); + // we assume realloc is always success + (*ans)[*retSize - 1] = malloc(2 * n + 1); + strcpy((*ans)[*retSize - 1], root->ans); } - for (int i = 0; i < n; i++) - { - free(dp[i]); - } - free(dp); + dfs(root->left, ans, n, retSize); + dfs(root->right, ans, n, retSize); +} + +void free_tree(tinode_t *root) +{ + if (root == NULL) + return; + free_tree(root->left); + free_tree(root->right); + free(root->ans); + free(root); +} + +char **generateParenthesis(int n, int *returnSize) +{ + char **result = NULL; + *returnSize = 0; + tinode_t *r = malloc(sizeof(tinode_t)); + r->ans = malloc(2); + r->right = NULL; + r->left = NULL; + strcpy(r->ans, "("); + dfs(r, &result, n, returnSize); + free_tree(r); + + return result; } \ No newline at end of file