AlgoMaster Logo

Generate Parentheses

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Recursive Approach

Intuition:

The problem asks us to generate all combinations of well-formed parentheses for a given number n, where n denotes the number of pairs of parentheses. A recursive approach can be used by considering two main constraints:

  • The number of '(' should be less than or equal to n.
  • The number of ')' should be less than or equal to the number of '('.

This approach uses a helper function to form parentheses while adhering to these constraints.

Steps:

  1. Define a helper function that takes the current string, the number of open parentheses, the number of close parentheses, and the result list.
  2. If the current string's length is equal to 2 * n, add the current string to the result list since we have a valid combination.
  3. If the number of open parentheses is less than n, append '(' to the current string and recursively call the helper function.
  4. If the number of close parentheses is less than the number of open parentheses, append ')' to the current string and recursively call the helper function.

Code:

2. Backtracking Approach

Intuition:

Backtracking is a smart way of pruning unnecessary paths early. This approach is similar to the recursive solution but takes advantage of backtracking by maintaining the valid string generation condition. We use an accumulator to build partial solutions and explore candidates.

Steps:

  1. Use a backtrack function to handle the creation of each string.
  2. At every call, utilize auxiliary variables to ensure the number of opening and closing brackets adheres to the constraints.
  3. Build the string incrementally and choose to either continue adding '(' or ')'.
  4. Whenever the conditions are violated, undo the previous step and attempt the next candidate.

Code: