classSolution{List<String> res =newLinkedList<>();publicList<String>generateParenthesis(int n){String str ="";int first =0,second =0;backtrack(str,first,second,n);return res;}voidbacktrack(String str,int first,int second,int n){if(first == n && second == n ){
res.add(newString(str));return;}for(int i =0;i <2;++i){if(first != n && i ==0){
str +="(";
first++;}elseif(first !=0&& first > second && i ==1){
str +=")";
second++;}else{continue;}backtrack(str,first,second,n);if(i ==0){
str = str.substring(0,str.length()-1);
first--;}else{
str = str.substring(0,str.length()-1);
second--;}}}}