Generating Parentheses Combinations with Backtracking

📌 Day 27/100 - Generate Parentheses (LeetCode 22) 🔹 Problem: Given n pairs of parentheses, generate all combinations of well-formed (balanced) parentheses. 🔹 Approach: Use backtracking to build strings character-by-character. Keep two counters: open = number of '(' used, close = number of ')' used. You may add '(' while open < n. You may add ')' while close < open (to maintain balance). When the current string length reaches 2*n, add it to the result list. 🔹 Complexity: Time: proportional to the number of valid combinations (Catalan number) — roughly O(4ⁿ / n^(3/2)). Space: output-sensitive — O(n * Cn) for storing results, and O(n) extra for recursion depth. 🔹 Key Learning: Backtracking is ideal when you need to enumerate valid combinations subject to constraints. Always enforce constraints early (here: close < open) to prune invalid branches. Think in terms of state (open/close counts) rather than raw string manipulation. #100DaysOfCode #LeetCode #Java #ProblemSolving #DSA

  • graphical user interface, text

To view or add a comment, sign in

Explore content categories