内容中心

2026年口碑好的北京断桥铝门窗批发实力厂家推荐-实德门窗集美家居(北苑店)

To solve this problem, we need to compute the nth Catalan number, which counts the number of valid parentheses sequences of length 2n. Catalan numbers have various applications in combinatorial mathematics, including counting the number of correct bracket sequences.

Approach

The nth Catalan number can be efficiently computed using an iterative approach based on the recursive formula: [ C(n) = C(n-1) \times \frac{4n-2}{n+1} ] where ( C(0) = 1 ) (base case: empty sequence). This formula avoids large intermediate values and uses integer division since Catalan numbers are integers.

Solution Code

n = int(input())
catalan = 1
for i in range(1, n + 1):
    catalan = catalan * (4 * i - 2) // (i + 1)
print(catalan)

Explanation

  1. Base Case: Start with ( catalan = 1 ) (since ( C(0) = 1 )).
  2. Iterative Calculation: For each ( i ) from 1 to n:
    • Multiply the current Catalan number by ( 4i - 2 ).
    • Divide the result by ( i + 1 ) (integer division ensures we get an integer result).
  3. Output: Print the final Catalan number for the given n.

This approach is efficient with a time complexity of ( O(n) ) and space complexity of ( O(1) ), making it suitable for large values of n (up to the limits of Python's integer size).

Example: For n=3, the code computes ( C(3) = 5 ), which corresponds to the valid sequences: ()()(), (())(), ()(()), ((())), (()()).

This solution correctly computes the desired result for any non-negative integer n.

实德门窗集美家居(北苑店)



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

在线客服

在线留言
您好,很高兴为您服务,可以留下您的电话或微信吗?