Backtracking
Medium

Generate Parentheses

Generate all combinations of well-formed parentheses.
Problem Understanding

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

Example: n = 3
Output: ["((()))","(()())","(())()","()(())","()()()"]

Algorithm Strategy

Instead of generating all $2^{2n}$ strings and validating them, we can build only valid strings.

Rules:

  1. Open: We can add an open parenthesis ( if open_count < n.
  2. Close: We can add a closing parenthesis ) if closed_count < open_count.

This ensures we never close more than we open (validity) and never exceed n (completeness).

Interactive Visualization
Step 1 / 1
Empty Heap

Initializing...

1x
See the Logic in Motion
Stop memorizing code. Unlock the full interactive visualizer to master the logic step-by-step.
Unlock VisualizerPREMIUM FEATURE

Stop Guessing, Start Mastering.

Build the FAANG intuition. Master this pattern with optimized implementations, visual dry runs, and our curated collection of high-yield problems.

Start Your Premium Prep