力扣第22题,回溯法,本地运行OK,提交后显示内存溢出。请大神指点

// 数字 n 代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且 有效的 括号组合。 统计过程中,左括号数大于等于右括号数。统计结束时,左右括号数相等

/*

输入:n = 3

输出:[

       "((()))",

       "(()())",

       "(())()",

       "()(())",

       "()()()"

     ]

*/

/* 回溯法 */

void dfs(char **res, char *array, int n, int left, int right, int *returnSize)

{

    if((left < right) || (left > n) || (right > n)) { // 此时不满足条件

        return;

    }

 

    if((left == n) && (right == n)) {

        res[*returnSize] = (char *)malloc(sizeof(char) * (2*n + 1));

        if(res[*returnSize] == NULL){

            return;

        }

        strcpy(res[*returnSize], array);

        printf("res[%d] = %s, strlen(res) = %d\n", *returnSize, res[*returnSize], (unsigned int)strlen(res[*returnSize]));

        (*returnSize)++;

        return;

    }

 

    array[strlen(array)] = '(';

    dfs(res, array, n, left + 1, right, returnSize);

    array[strlen(array)-1] = '\0';

 

    array[strlen(array)] = ')';

    dfs(res, array, n, left, right + 1, returnSize);

    array[strlen(array)-1] = '\0';

}

 

char ** generateParenthesis(int n, int* returnSize) 

{

    char *array = (char *)malloc(sizeof(char) * (2*n + 1));

    if(array == NULL){

        return NULL;

    }

    memset(array, '\0', sizeof(char) * (2*n + 1));

    char **res = (char **)malloc(sizeof(char *) * 2000);

    if(res == NULL){

        return res;

    }

    dfs(res, array, n, 0, 0, returnSize);

    free(array);

    return res;

}

 

int main(void)

{

    int n = 7;

    int num = 0;

    char **res = generateParenthesis(n, &num);

    printf("num = %d\n", num);

    system("pause");

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值