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
- 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.
- Two rules keep every prefix valid. Add
(while fewer than n are open; add)only whileclosedN < 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. - 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.
- Pitfall: checking
closedN < ninstead ofclosedN < openNlets)(through. The close rule compares with the opens so far, not with n. - Why the Stack category: the shared
stackis pushed before each call and popped after it, the same undo step every backtracking solution uses.