Balanced Paranthesis

QUESTION

Write a function to generate all possible n pairs of balanced parentheses.\n\nFor example, if n=1\n{}\nfor n=2\n{}{}\n{{}}.

ANSWER

#include <stdio.h>
# include<stdio.h>
# define MAX_SIZE 100
 
void _printParenthesis(int pos, int n, int open, int close);
 
// Wrapper over _printParenthesis()
void printParenthesis(int n)
{
    if(n > 0)
        _printParenthesis(0, n, 0, 0);
    return;
}    
 
void _printParenthesis(int pos, int n, int open, int close)
{
    static char str[MAX_SIZE];   
     
    if(close == n) 
    {
        printf("%s \n", str);
        return;
    }
    else
    {
        if(open > close) 
        {
            str[pos] = '}';
            _printParenthesis(pos+1, n, open, close+1);
        }
         
        if(open < n)
        {
        str[pos] = '{';
        _printParenthesis(pos+1, n, open+1, close);
        }
    }
}
 
// Driver program to test above functions
int main()
{
    int n ;
  scanf("%d",&n);
    printParenthesis(n);
    getchar();
    return 0;
}
Ads Blocker Image Powered by Code Help Pro

Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.

Powered By
CHP Adblock Detector Plugin | Codehelppro