您的位置:首页 > 其它

LeetCode 10.9 Generate Parentheses

2016-04-27 10:08 253 查看
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++;		}	}}
                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: