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:
"((()))", "(()())", "(())()", "()(())", "()()()"
solution:DFS模版
package leetcode2;import java.util.ArrayList;public class Generate_parenthese { public static ArrayListgenerateParenthesis(int n) { ArrayList reArrayList=new ArrayList (); String s=new String(); dfs(reArrayList,s,n,n); //DFS的模版递归 dfs(list ,E,deep,somethingConstant) return reArrayList; } public static void dfs(ArrayList reArrayList, String s, int left,int right) { // TODO Auto-generated method stub // 先考虑deep极值,此处为left,right个数,直接return if(right 0){ dfs(reArrayList, s+'(', left-1, right); } if(right>0){ dfs(reArrayList, s+')', left, right-1); } } public static void main(String[] args) { // TODO Auto-generated method stub System.out.println(generateParenthesis(3)); }}