22. Generate Parentheses

Photo by Calum Lewis on Unsplash
Photo by Calum Lewis on Unsplash
This problem asks us to list all possible combinations of parentheses, so we can use backtracking to solve it.

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

This problem asks us to list all possible combinations of parentheses, so we can use backtracking to solve it. While backtracking can find all combinations, some combinations are illegal. The following is a legal parenthesis combination.

Let’s look at an illegal parenthesis combination. Putting a closing parenthesis at the beginning makes it impossible to get a legal combination no matter how you put it later. According to this example, we can observe that when the remaining number of closing parenthesis is greater than or equal to the remaining number of opening parenthesis, we cannot put closing parenthesis.

Backtracking

  • Time: O(2^2n)
  • Space: O(n)
class Solution {
    public List<String> generateParenthesis(int n) {
        List<String> results = new ArrayList<>();
        dfs(n, n, new StringBuilder(), results);
        return results;
    }

    private void dfs(int left, int right, StringBuilder prefix, List<String> results) {
        if (left == 0 && right == 0) {
            results.add(prefix.toString());
        }

        if (left > 0) {
            prefix.append('(');
            dfs(left - 1, right, prefix, results);
            prefix.deleteCharAt(prefix.length() - 1);
        }

        if (right > left) {
            prefix.append(')');
            dfs(left, right - 1, prefix, results);
            prefix.deleteCharAt(prefix.length() - 1);
        }
    }
}

Reference

Leave a Reply

Your email address will not be published. Required fields are marked *

You May Also Like
Photo by Guilherme Stecanella on Unsplash
Read More

62. Unique Paths

This problem asks us to calculate the total number of all possible paths from the top-left corner to the bottom-right corner. We can observe that to go from the top-left corner to the bottom-right corner, the robot can only go right or down.
Read More