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

In memoriam Viktor Mikhailovich Vasnetsov: 2, 1887-1926

More paintings of Russian and Slavic legends and folk tales, including Bogatyrs, Ivan Tsarevich and the Grey Wolf, Sleeping Beauty, and the Frog Princess.

via The Eclectic Light Company

Powerful AIs might escape containment by releasing themselves as open-weight models

Before large language models, people who worried about AI safety often talked about the “boxing problem”. It goes like this. Suppose some genius figures out artificial intelligence in a late-night coding session on their laptop. Because they’re a genius, they’re smart enough to disable internet acce...

via Sean Goedecke

AI in Linux

The role of AI tools (LLMs, mainly) in Linux is under discussion, or it was, until Linus Torvalds “put his foot down” in support of the use of AI in Linux kernel development. I can identify two major ways in which AI is used for Linux kernel development: authoring code and reviewing code. There are,...

via Drew DeVault