![]() |
VOOZH | about |
Given an integer n, find the number of valid parentheses expressions of length n.
Examples :
Input: n = 2
Output: 1
Explanation: There is only one possible valid expression of length 2, "()"Input: n = 4
Output: 2
Explanation: Possible valid expression of length 4 are "(())" and "()()"Input: n = 6
Output: 5
Explanation: Possible valid expressions are "((()))", "()(())", "()()()", "(())()" and "(()())"
Table of Content
Breakdown:
For a valid parentheses string, the number of opening brackets (is always equal to the number of closing brackets). This immediately implies that if n is odd, it is impossible to form a valid arrangement, because parentheses come in pairs.
Do we really need to generate the entire string like "(())" ?
To count the number of valid parentheses, it is enough to keep track of the number of opening and closing brackets left to place. We don’t care about the exact string unless we want to print all arrangements—just the counts are enough to ensure validity.
The idea is to place the opening and closing brackets while maintaining validity. At each step, we can either place an opening bracket (if any are left) or a closing bracket (only if the number of remaining closing brackets is greater than the number of remaining opening brackets). This ensures that the partially formed string is always valid, and by recursively exploring these choices and count all possible valid arrangements.
5
To generate valid parentheses sequences, we only need to keep track of two quantities while building the sequence:
At each step, we can choose to place either an opening or a closing bracket, and we reduce the corresponding count. By maintaining these two states, we ensure that every choice keeps the sequence valid.
We define the DP state as:
dp[open][close] = number of ways to form valid parentheses using open opening brackets and close closing brackets still left.
Key rule: close >= open to ensure sequences remain valid.
Base case: if open = 0, there’s only one way: place all remaining closing brackets.
Recurrence:
dp[open][close] = dp[open-1][close] + dp[open][close-1]
5
If n is odd, it is impossible to form valid parentheses because parentheses always come in pairs. If n is even, there are n/2 pairs of parentheses so the problem reduces to arranging these n/2 pairs in all possible valid ways.
The idea is to use Catalan number to find the number of ways to arrange n/2 pairs of parentheses so that the resulting sequence is valid.
The nth Catalan number can be calculated using the formula:
5