Leetcode Generate Parentheses problem solution in C programming

In the Leetcode Generate Parentheses problem solution in C programming Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

Leetcode Generate Parentheses problem solution in C programming

int count=-1;
void func(int n,int index,char **ans,char *temp,int start,int end){
    if(start==n&&end==n){
        temp[2*n]='\0';
        ++count;
        ans[count]=(char *)malloc(sizeof(char)*((2*n)+1));
        memset(ans[count],0,sizeof(char)*((2*n)+1));
        strcpy(ans[count],temp);  
        return;
    }
    if(start<n){
        temp[index]='(';
        func(n,index+1,ans,temp,start+1,end); 
    } 
    if(start>end){
        temp[index]=')';
        func(n,index+1,ans,temp,start,end+1);
    }
}
char ** generateParenthesis(int n, int* returnSize){
    char **ans=(char **)malloc(sizeof(char *)*1500);
    memset(ans,0,sizeof(char*)*1500);
    char *temp=(char *)malloc(sizeof(char)*((2*n)+1));
    memset(temp,0,sizeof(char)*((2*n)+1));
    count=-1;
    func(n,0,ans,temp,0,0);
    *returnSize=count+1;
    free(temp);
    return ans;
}

Also read,

By Neha Singhal

Hi, my name is Neha singhal a software engineer and coder by profession. I like to solve coding problems that give me the power to write posts for this site.

Leave a Reply

Your email address will not be published. Required fields are marked *