[Leetcode Series] [algorithm] different [medium] binary search tree (mathematics to solve)

topic:

Topic links:  https://leetcode-cn.com/problems/unique-binary-search-trees/

 

Problem-solving ideas:

The number of different types of binary search, in line with Cattleya number, also known as Catalan number , general term formula is:

C_{n + 1} = C_{0}C_{n} + C_{1}C_{n - 1} + ... + C_{n}C_{0} = \sum _{i = 0}^{n}C_{i}C_{n - i} = \frac {2(2n + 1)}{n + 2}C_{n}\approx \frac {4^{n}}{n^{\frac {2}{3}}\sqrt{\pi }}

Directly into the formula, you can obtain any of

 

Code:

class Solution:
    def numTrees(self, n: int) -> int:
        res = 1
        for i in range(n):
            res = res * 2 * (2 * i + 1) // (i + 2)
        
        return res

 

Published 100 original articles · won praise 4 · Views 1461

Guess you like

Origin blog.csdn.net/songyuwen0808/article/details/105396796