Generate Parentheses


Generate Parentheses – LeetCode


Problem: Generate Parentheses

Problem Statement

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


Examples

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

Example 2
Input: n = 1
Output: ["()"]


Constraints


Intuition

We need to generate all valid combinations of n opening and n closing brackets.
A combination is valid if:

This is a classic case for the Input-Output Method:


Input-Output Recursive Method

Function Signature

void helper(int open, int close, String output, List<String> ans)

Parameters:


Base Case

If open == 0 and close == 0:


Recursive Choices

  1. If open > 0:

    • We can safely add "("helper(open - 1, close, output + "(", ans)
  2. If close > open:

    • Only if we’ve already placed more opening brackets, we can add ")"
      helper(open, close - 1, output + ")", ans)

Code (Java)

class Solution {
    public List<String> generateParenthesis(int n) {
        List<String> ans = new ArrayList<>();
        helper(n, n, "", ans);
        return ans;
    }

    private void helper(int open, int close, String output, List<String> ans) {
        // Base case
        if (open == 0 && close == 0) {
            ans.add(output);
            return;
        }

        // Choice 1: Add opening bracket
        if (open > 0) {
            helper(open - 1, close, output + "(", ans);
        }

        // Choice 2: Add closing bracket
        if (close > open) {
            helper(open, close - 1, output + ")", ans);
        }
    }
}

Time and Space Complexity


Dry Run

Input: n = 2

Start: open = 2, close = 2, output = ""

Step 1: Add "(" → open = 1, close = 2 → "("
Step 2: Add "(" → open = 0, close = 2 → "(("
Step 3: Add ")" → open = 0, close = 1 → "(()"
Step 4: Add ")" → open = 0, close = 0 → "(())" → valid

Backtrack

Step 2: Add ")" → open = 1, close = 1 → "()"  
Step 3: Add "(" → open = 0, close = 1 → "()("  
Step 4: Add ")" → open = 0, close = 0 → "()()" → valid

Output: ["(())", "()()"]


Conclusion

This problem is a classic example of the input-output recursion model, where decisions (include/exclude) are made based on constraints. The bracket generation logic is based on careful constraint checking and demonstrates the power of controlled recursive tree traversal.