// This file is generated by mkfile.py
// Date: 2026-06-25

#include <solution/22.h>
#include <stdlib.h>
#include <string.h>

typedef struct tinode_t
{
    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')
    {
        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);
    }

    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;
}