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:
"((()))", "(()())", "(())()", "()(())", "()()()"
用dfs思想做递归就好了,记好了先写base case,left,right走过一遍了,可以把这个String加进list
Import Java.util.arraylist;import Java.util.list;public class Generateparentheses {public static void main (String args[ ]) {generateparentheses GP = new generateparentheses (); System.out.println (Gp.generateparenthesis (3));} Public list<string> generateparenthesis (int n) {if (n<=0) return null; Arraylist<string>list = new arraylist<string> (); String str = new string ();d FS (list,str,n,n); return list; } Private Voiddfs (arraylist<string> list, String str, int left, int. right) {if (left>right) Return;//problem with ") ("if (left==0&&right==0) {list.add (str);} if (left>0) DFS (list,str+ "(", Left-1,right), if (right>0) DFS (list, str+ ")", Left,right-1);}}
"Leetcode" Generate parentheses in JAVA