AskHandle

AskHandle Blog

How Can We Generate All Valid Parentheses Combinations?

February 19, 2025Nina Kimes3 min read

How Can We Generate All Valid Parentheses Combinations?

Generating all valid combinations of parentheses is a classic problem in computer science and often appears in coding interviews. The challenge is to create combinations of parentheses that are balanced — meaning that for every opening parenthesis, there is a closing parenthesis that follows and there are no unmatched closing parentheses.

To tackle this, we can use a recursive backtracking approach. This method allows us to build the combinations step by step and only include valid parentheses during the process. Let's break down the steps involved in this approach.

Understanding the Problem

Given a number n, which represents the number of pairs of parentheses, our goal is to produce all combinations of well-formed parentheses. For instance, if n=3, the valid combinations are:

  • ((()))
  • (()())
  • (())()
  • ()(())
  • ()()()

The Recursive Approach

We can visualize our approach as making a choice at each position in the combination:

  1. If the number of opening parentheses used so far is less than n, we can add an opening parenthesis (.
  2. If the number of closing parentheses used is less than the number of opening parentheses, we can add a closing parenthesis ).

By tracking the counts of both parentheses, we ensure that we only create valid combinations.

Implementation

Here’s a Python function that implements the above logic using recursion:

python
1def generateParenthesis(n):
2    def backtrack(S='', left=0, right=0):
3        if len(S) == 2 * n:
4            results.append(S)
5            return
6        if left < n:
7            backtrack(S + '(', left + 1, right)
8        if right < left:
9            backtrack(S + ')', left, right + 1)
10
11    results = []
12    backtrack()
13    return results
14
15# Example usage:
16n = 3
17print(generateParenthesis(n))

Breakdown of the Code

  1. Function Definition: The main function generateParenthesis initializes an empty list results to store valid combinations and calls the backtrack helper function.

  2. Helper Function backtrack:

    • It takes the current string S, counts of left parentheses left, and counts of right parentheses right as parameters.
    • Base Case: If the length of S equals 2 * n, it means we have a valid combination of parentheses, which is then added to the results.
    • The function checks if more opening parentheses can be added by comparing left to n.
    • It adds a closing parenthesis if there are more opening parentheses than closing ones by comparing right with left.

Complexity Analysis

The time complexity of this algorithm can be estimated as O(4^n / sqrt(n)), which arises from the structure of the combinations formed. The space complexity is O(n) due to the recursion stack and storing the results.