Generate Parentheses

Problem

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

Example 1:

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

Example 2:

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

Constraints:

  • 1 <= n <= 8

Solution

Backtracking is actually super fun.

class Solution {
    public List<String> generateParenthesis(int n) {
        var answers = new ArrayList<String>();
        solve(n, 0, "", answers);
        return answers;
    }

    public void solve(int n, int depth, String current, List<String> answers) {
        // at each point, we can choose to nest or not.
        if (n == 0) {
            // close out this depth
            for (int i = 0; i < depth; i++) {
                current = current + ")";
            }

            answers.add(current);
            return;
        }

        // nest
        solve(n - 1, depth + 1, current + "(", answers);

        // close out
        for (int i = 1; i < depth + 1; i++) {
            current = current + ")";
            solve(n - 1, depth - i + 1, current + "(", answers);
        }
    }
}

Recent posts from blogs that I like

Concurrent Servers: Part 7 - Rust

This is part 7 in a series of posts on writing concurrent network servers. In this part, we discuss how the challenges described in earlier parts are tackled in the Rust programming language. All posts in the series: Part 1 - Introduction Part 2 - Threads Part 3 - Event-driven Part 4 - libuv Part 5 ...

via Eli Bendersky

A volcanic weekend of paintings 1 Fuji to Hekla

Mount Fuji by Hokusai, Naotake, Hiroshige, and pioneer botanical painter Marianne North. Childe Hassam's Mounts Adams and St Helens, Church's Cotopaxi, and others.

via The Eclectic Light Company

Amp is so good and so bad

The highs and lows of using Amp and its remote-first approach to software development.

via Jacob Woliver