22
Gitea CTest Workflow / test (push) Waiting to run

This commit is contained in:
2026-06-25 23:13:44 +08:00
parent 576970541c
commit 4e0f032e14
+83 -8
View File
@@ -4,18 +4,93 @@
#include <solution/22.h> #include <solution/22.h>
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
char **generateParenthesis(int n, int *returnSize)
typedef struct tinode_t
{ {
char **dp = malloc(sizeof(char *) * n); char *ans;
for (int i = 0; i < n; i++) struct tinode_t *left;
struct tinode_t *right;
} tinode_t;
int get_number_of(char *s, char c)
{ {
dp[i] = malloc(sizeof(char) * (n + 1)); int num = 0;
memset(dp[i], 0, n + 1); while (*s != '\0')
{
if (*s == c)
num++;
s++;
}
return num;
} }
for (int i = 0; i < n; i++) void dfs(tinode_t *root, char ***ans, int n, int *retSize)
{ {
free(dp[i]); 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;
} }
free(dp); 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);
}
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;
} }