Generate Parentheses

Test cases giving wrong answers, couldnt find the mistake

#include<iostream>
#include<algorithm>
#include<string>
#include<stdio.h> 
#include<stdlib.h>
#include<cstring>
#include<ctype.h>
#include<math.h>
#include<vector>
#include<time.h>
using namespace std;
typedef long long int ll;
bool printsol(char a[],int n,int i)
{
	//base
	if(i==2*n-1)
	{
		//print
		cout<<a<<endl;
		return false;
	}
	//no swap
	if(printsol(a,n,i+2))
	return true;
	//swap
	for(int k=i+1;k<2*n;k+=2)
	{	
		if(a[k]=='(')
		{
		swap(a[i],a[k]);
		if(printsol(a,n,i+2))
		return true;
		swap(a[i],a[k]);	
		}
		
	}
	return false;
}
int main() {
char a[23];
int n;
cin>>n;
for(int i=0;i<2*n;i+=2)
{
	a[i]='(';
	a[i+1]=')';
}
a[2*n]='\0';
bool p=printsol(a,n,1);
return 0;
}

Hello @saarthakrox29,

  1. Share you code through an online IDE (Coding Blocks IDE).

  2. Following will help in correcting the code:
    Take two variables to count the occurrence of closing and opening bracket.
    Recursive APProach:
    2.1. base case i.e. printing the balanced string of parenthesis
    when close == n
    2.2. insert a closing ‘)’ parenthesis if there is an opening ‘(’ parenthesis already present in the output string or char array.
    when open > close
    2.3. insert a opening ‘(’ parenthesis if we can insert more brakets.
    when open < n

    the position of 2.2. and 2.3. will affect the order in which the balanced parenthesized will appear.
    Suggestion:
    Try to swap their positions to understand it better.

Hope, this would help.
Give a like if you are satisfied.

1 Like

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.