To solve this problem, we need to determine the number of valid parentheses sequences that can be formed using n pairs of parentheses. This is a classic problem that can be efficiently solved using the Catalan numbers, which are a sequence of natural numbers that have many applications in combinatorial mathematics.
Approach
The nth Catalan number gives the number of valid parentheses sequences of length 2n. The formula for the nth Catalan number is:
[ C(n) = \frac{1}{n+1} \binom{2n}{n} ]
where (\binom{2n}{n}) is the binomial coefficient (number of ways to choose n elements from 2n elements).
Key steps:
- Compute the binomial coefficient (\binom{2n}{n}).
- Divide the result by
n+1to get the nth Catalan number.
Solution Code
import math
n = int(input())
catalan = math.comb(2 * n, n) // (n + 1)
print(catalan)
Explanation
- Binomial Coefficient: The binomial coefficient (\binom{2n}{n}) calculates the number of ways to arrange
2nelements (n opening and n closing parentheses) without any restrictions. - Catalan Number: Dividing by
n+1filters out the invalid sequences (those where closing parentheses exceed opening ones at any point), giving the count of valid sequences.
For example:
- If
n=3, the result is (C(3) = \frac{1}{4} \times \binom{6}{3} = \frac{20}{4} =5), which corresponds to the valid sequences:((())),(()()),(())(),()(()),()()().
This approach efficiently computes the result using Python's built-in math.comb function (available in Python 3.10+), which handles large numbers well due to Python's support for arbitrary-precision integers.
Answer: The code will output the number of valid parentheses sequences for the given n. For example, if input is 3, output is 5.
\boxed{5} (for input 3; replace with the actual output based on input)


作者声明:本文包含人工智能生成内容。