leetcode (22) - Generate Parentheses

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

For example, given n = 3, a solution set is:

[
  "((()))",
  "(()())",
  "(())()",
  "()(())",
  "()()()"
]

/**
 * Return an array of size *returnSize.
 * Note: The returned array must be malloced, assume caller calls free().
 */
void generate(char** res,int* size,int l,int r,char* tmp,int index){   // l和r记录剩余左右括号的数量
    if(l==0 && r==0){    // 当且仅当左右括号数量为0时,正常结束
        tmp[index]='\0';
        res[*size]=(char*)malloc(sizeof(char)*index);
        strcpy(res[*size],tmp);
        (*size)++;
        return;
    }
    if(l>0){
        tmp[index]='(';
        generate(res,size,l-1,r,tmp,index+1);   //每一层递归只有这一行函数结束了,才进行下面的if(r>0 && l<r)。再考虑最外层,也是如此。
    }
    if(r>0 && l<r){     //剩余右括号数量比左括号多时,才能添加右括号
        tmp[index]=')';
        generate(res,size,l,r-1,tmp,index+1);
    }
}


char** generateParenthesis(int n, int* returnSize) {
    char** res;
    char* tmp=(char*)malloc(sizeof(char)*(n*2+1));
    int l=n,r=n;
    res=(char**)malloc(sizeof(char*)*1000000);
    *returnSize=0;
    generate(res,returnSize,l,r,tmp,0);
    return res;
}


凑着这篇文章,理解一下递归:

递归的结束条件:  栈顶,一层一层的往回返,一直返回到最外层

递归的过程:         压栈,参数变化,参数可看作全局变量

每一层递归:          改变参数





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值