Question goes like this :
input: 1
output:
{}
input: 2
output:
{}{}
{{}}
input: 3
output:
{}{}{}
{{}}{}
{}{{}}
This is my program :
public class PrintBraces {
int n;
char []braces;
void readData()
{
java.util.Scanner scn=new java.util.Scanner(System.in);
System.out.print("Please enter the value of n : ");
n=scn.nextInt();
}
void manipulate()
{
braces=new char[n*2];
for(int i=0;i<2*n;i+=2)
{
braces[i]='{';
braces[i+1]='}';
}
for(int i=0;i<n;i++)
{
int oddNo=2*i-1;
if(oddNo>0)
{
char temp=braces[oddNo];
braces[oddNo]=braces[oddNo+1];
braces[oddNo+1]=temp;
print();
temp=braces[oddNo];
braces[oddNo]=braces[oddNo+1];
braces[oddNo+1]=temp;
}
else
{
print();
}
}
}
void print()
{
for(int i=0;i<2*n;i++)
{
System.out.print(braces[i]);
}
System.out.println();
}
}
class PrintMain
{
public static void main(String args[])
{
PrintBraces pb=new PrintBraces();
pb.readData();
pb.manipulate();
}
}
As expected, I get the correct answer.
I have solved it but I think it isn't efficient enough. Can anyone optimise it? And I would love to see any other alternative approaches for the same problem. May be a recursive one? Also, I am open to any suggestions for improving my programming style. Any good practices that I may be violating in my code?
3
contain{{{}}}
? Are only two levels of nesting allowed? \$\endgroup\$