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

Naturalists: Sorolla and Zorn

Around 1890, two aspiring painters passed through a phase of Naturalism: in Spain, Joaquín Sorolla, and in Sweden, Anders Zorn, both on their way to become masters.

via The Eclectic Light Company

Moving away from Tailwind, and learning to structure my CSS

Hello! 8 years ago, I wrote excitedly about discovering Tailwind. At that time I really had no idea how to structure my CSS code and given the choice between a pile of complete chaos and Tailwind, I was really happy to choose Tailwind. It helped me make a lot of tiny sites! I spent the last week or ...

via Julia Evans

Add an LLM policy for rust-lang/rust

No comment on this PR may mention the following topics: Long-term social or economic impact of LLMs The environmental impact of LLMs Anything to do with the copyright status of LLM output Moral judgements about people who use LLMs We have asked the moderation team to help us enforce these rules. – A...

via Drew DeVault