public class Solution { public static ArrayListgenerateParenthesis(int n) { ArrayList list = new ArrayList (); StringBuilder str = new StringBuilder(); if (n == 0) { return list; } recursive(0, 0, n, str, list); return list; } public static void recursive(int left, int right, int n, StringBuilder str, ArrayList list) { if (left < right) { return; } if (left == n && right == n) { String tmp = str.toString(); list.add(tmp); return; } if (left < n) { StringBuilder newstr = new StringBuilder(str.toString()); newstr.append('('); recursive(left + 1, right, n, newstr, list); } if (right < n) { StringBuilder newstr = new StringBuilder(str.toString()); newstr.append(')'); recursive(left, right + 1, n, newstr, list); } } }