Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
For example, given n = 3, a solution set is:
"((()))", "(()())", "(())()", "()(())", "()()()"
import java.util.Iterator;
import java.util.Stack;
public class T5 {
public static void main(String[] args) {
T5 t=new T5(6);
t.DFS(0);
t.print();
}
Stack<int [] > ans=new Stack<>();
int n;
int[] f;
int pre=-1;
T5(int _n){
n=_n;
f=new int[n];
}
void DFS(int k){
if(k==n){
int[] arr=new int[n];
for(int i=0;i<n;i++){
arr[i]=f[i];
}
ans.add(arr);
}else{
for(int i=pre==-1?0:pre;i<n;i++){
if(k<=i){
pre=i;
f[k]=i+1;
DFS(k+1);
}
}
}
}
void print(){
int num=1;
Iterator<int[]> it = ans.iterator();
while(it.hasNext()){
System.out.println("======"+num+"=====");
int []temp=it.next();
String s="";
int l=n;
while(l-->0){
s+="(";
}
for(int i=temp.length-1;i>=0;i--){
s=s.substring(0, temp[i])+")"+s.substring(temp[i]);
}
System.out.println(s);
num++;
}
}
}