Skip to content

Latest commit

 

History

History
79 lines (58 loc) · 1.64 KB

96.md

File metadata and controls

79 lines (58 loc) · 1.64 KB

96 Unique Binary Search Trees

Description

link


General Type

Catalan Numbers


Solution

Catalan:

根据《组合数学》中,定理8.1.1:有正1和负1各n个组成的序列,要求部分和总大于0。这样序列个数称作catalan数

通项公式为:h(n) = C(2n, n)/(n+1)

递推公式为:h(0)=1,h(1)=1,h(n)= h(0)*h(n-1)+h(1)*h(n-2) + ... + h(n-1)*h(0) ,(n>=2)


Code

class Solution:
    def numTrees(self, n):
        """
        :type n: int
        :rtype: int
        """
        res = [1] + [0 for _ in range(n)]
        
        for i in range(1,n+1):
            res[i] = sum([res[i-j-1]*res[j] for j in range(i)])
        return res[n]

Follow UP

print all trees

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def generateTrees(self, n):
        """
        :type n: int
        :rtype: List[TreeNode]
        """
        if not n:
            return []
        return self.dfs(1,n)
    
    def dfs(self, s, e):
        if s > e:
            return [None]
        res = []
        for i in range(s,e+1):
            for l in self.dfs(s,i-1): # kind of fast sort
                for r in self.dfs(i+1,e): # divided nodes into two parts and reunion them
                    node = TreeNode(i)
                    node.left = l
                    node.right = r
                    res.append(node)
        return res