LeetCode 22 · Medium · Stack

Generate Parentheses

Given n, return every string of n pairs of parentheses that is well formed: read left to right, no ) ever closes more than has been opened, and all of them close by the end.

O(4ⁿ / √n)time (Catalan many answers)
O(n)space besides the output
open < n, closed < openthe only two rules

n from 1 to 4 · n = 4 already grows a 101-node tree, n = 5 would need 309

openNclosedN

stack the string built on the current path

decision tree left edge adds “(”, right edge adds “)” · dashed: o=n means no “(” left · c=o means a “)” would close nothing

res 0 strings

private List<String> res = new ArrayList<>();private StringBuilder stack = new StringBuilder();public List<String> generateParenthesis(int n) { backtrack(0, 0, n); return res;}private void backtrack(int openN, int closedN, int n) { if (openN == n && closedN == n) { res.add(stack.toString()); return; } if (openN < n) { stack.append('('); backtrack(openN + 1, closedN, n); stack.deleteCharAt(stack.length() - 1); } if (closedN < openN) { stack.append(')'); backtrack(openN, closedN + 1, n); stack.deleteCharAt(stack.length() - 1); }}
openN
0
closedN
0
stack
""
res.size()
0

Why it works

  1. Brute force writes all 2²ⁿ strings of length 2n and keeps the valid ones with a balance check, O(n · 4ⁿ). For n = 4 that is 256 strings to find 14.
  2. Two rules keep every prefix valid. Add ( while fewer than n are open; add ) only while closedN < openN. A prefix that obeys both can always be finished, so every leaf the search reaches is an answer and no branch is wasted beyond one pruned check.
  3. Output-sized work. The answers are the Catalan numbers, about 4ⁿ / (n√n) of them, each copied in O(n): O(4ⁿ / √n) time. The stack never holds more than 2n characters.
  4. Pitfall: checking closedN < n instead of closedN < openN lets )( through. The close rule compares with the opens so far, not with n.
  5. Why the Stack category: the shared stack is pushed before each call and popped after it, the same undo step every backtracking solution uses.