leetcode (22) - Generate Parentheses

来源:互联网 发布:西门子plc编程软件下载 编辑:程序博客网 时间:2024/05/29 10:10

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