β Generate all parentheses(Contest)
Generate all parentheses easy Time Limit: 2 sec Memory Limit: 128000 kB
Problem Statement :
Given an integer N, print all balanced bracket strings of length 2*N. A bracket string is a string that contains only '(' and ')' as its characters.
Empty string is a balanced bracket string
If S is a balanced bracket string, so is (S)
If S and T are balanced bracket strings, so is ST Print in lexicographical order. '(' appears before ')' in lexicographical orderInputThe single line of input containing an integer N. 1 <= N <= 15OutputPrint all possible balanced bracket strings of length 2*N in a separate line.ExampleSample Input 1: 1 Sample Output 1: () Sample Input 2: 3 Sample Output 2: ((())) (()()) ()(()) ()()() Explanation: It is printed in lexicographical order .
link:https://my.newtonschool.co/playground/code/sapyq16sbt10/
import java.io.*; // for handling input/output
import java.util.*; // contains Collections framework
// don't change the name of this class
// you can add inner classes if needed
class Main {
public static ArrayList generateParenthesis(ArrayList<String> list1,int n){
if(n==1)
return list1;
else{
ArrayList<String>list2 = new ArrayList<>();
for(int i=0;i<list1.size();i++)
list2.add("(" + list1.get(i) + ")");
for(int i=0;i<list1.size();i++)
list2.add("()" + list1.get(i));
return generateParenthesis(list2, n-1);
}
}
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
ArrayList<String> list1= new ArrayList<>();
list1.add("()");
list1 = generateParenthesis(list1,n);
for(int i =0;i<list1.size();i++)
System.out.println(list1.get(i));
}
}
Last updated