classSolution{ public List<String> generateParenthesis(int n){ List<String> res = new ArrayList<>(); if (n == 0) return res; helper(n, res, 0, 0, ""); return res; } privatevoidhelper(int n, List<String> res, int left, int right, String cur){ if (left == n && right == n) { res.add(cur); return; } int maxLeft = n - left; if (maxLeft > 0){ cur += "("; helper(n, res, left + 1, right, cur); if (cur.length() > 1) cur = cur.substring(0, cur.length() - 1); else cur = ""; } int maxRight = left - right; if (maxRight > 0){ cur += ")"; helper(n, res, left, right + 1, cur); if (cur.length() > 1) cur = cur.substring(0, cur.length() - 1); else cur = ""; } } }