Algo-Sim › Recursion & Backtracking

Generate Parentheses

Medium · Recursion & Backtracking · step through it in Java, Python and C++ on your own input

Generate every well-formed string of n pairs of parentheses by choosing, exploring, and undoing.

Problem

Given n, return every string of n opening and n closing parentheses that is well-formed: reading left to right, the closes never outnumber the opens. Any order is accepted.

Constraints

Edge cases to test

Follow-up questions

Why is it O(4ⁿ / √n)?
The output has Catalan(n) strings of length 2n, and the two pruning rules (open < n, close < open) mean no branch is wasted.
Is there a DP formulation?
Every string is (A)B with A of i pairs and B of n − 1 − i pairs: build from smaller lists.

Solution

Java

List<String> result = new ArrayList<>();

List<String> generateParenthesis(int n) {
    backtrack(new StringBuilder(), 0, 0, n);
    return result;
}

void backtrack(StringBuilder cur, int open, int close, int n) {
    if (cur.length() == 2 * n) {
        result.add(cur.toString());
        return;
    }
    if (open < n) {
        cur.append('(');
        backtrack(cur, open + 1, close, n);
        cur.deleteCharAt(cur.length() - 1);
    }
    if (close < open) {
        cur.append(')');
        backtrack(cur, open, close + 1, n);
        cur.deleteCharAt(cur.length() - 1);
    }
}

Python

def generate_parenthesis(n):
    result = []

    def backtrack(cur, open_count, close_count):
        if len(cur) == 2 * n:
            result.append("".join(cur))
            return
        if open_count < n:
            cur.append("(")
            backtrack(cur, open_count + 1, close_count)
            cur.pop()
        if close_count < open_count:
            cur.append(")")
            backtrack(cur, open_count, close_count + 1)
            cur.pop()

    backtrack([], 0, 0)
    return result

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    vector<string> result = {};

    vector<string> generateParenthesis(int n) {
        string cur;
        backtrack(cur, 0, 0, n);
        return result;
    }

    void backtrack(string &cur, int open, int close, int n) {
        if (int(cur.size()) == 2 * n) {
            result.push_back(cur);
            return;
        }
        if (open < n) {
            cur.push_back('(');
            backtrack(cur, open + 1, close, n);
            cur.pop_back();
        }
        if (close < open) {
            cur.push_back(')');
            backtrack(cur, open, close + 1, n);
            cur.pop_back();
        }
    }
};

More Recursion & Backtracking problems