Hello Guys I was making a program of "Generate all parenthesis" and I got the error message as:-"java.base/java.lang.StringConcatHelper.simpleConcat(StringConcatHelper.java:421)"
along with this I am getting error of stack overflow
I am attaching a code with this error please see to it and tell me the modification if needed:-
public class j{
public static void main(String[] args){
int n = 2;
int open = n;
int close = n;
String op = " ";
findAns(op, open, close);
}
private static void findAns(String op, int open, int close){
if (open == 0 && close == 0){
System.out.println(op);
}
if (open == close){
String op1 = op + "(";
findAns(op1, open - 1, close);
return;
}
if (open != 0){
String op1 = op + "(";
open = open - 1;
findAns(op1, open, close);
}
String op1 = op + ")";
close = close - 1;
findAns(op1, open, close);
return;
} }
You need an exit condition for your recursion. Maybe this?
if (open == 0 && close == 0){
System.out.println(op);
--> return;
}