描述

给定一个整数 n,求以 1 … n 为节点组成的二叉搜索树有多少种?

示例:

输入: 3
输出: 5
解释:
给定 n = 3, 一共有 5 种不同结构的二叉搜索树:

   1         3     3      2      1
    \       /     /      / \      \
     3     2     1      1   3      2
    /     /       \                 \
   2     1         2                 3

Python

Suppose you are given 1–n, and you want to generate all binary search trees.
How do you do it? Suppose you put number i on the root, then simply
Generate all BST on the left branch by running the same algorithm with 1–(i-1),
Generate all BST on the right branch by running the same algorithm with (i+1)–n.
Take all combinations of left branch and right branch, and that’s it for i on the root.
Then you let i go from 1 to n. And that’s it.

易懂版本,但是速度过慢,递归通病

    def numTrees(self,n):
        if n == 0:
            return 1
        if n == 1:
            return 1

        Result = 0
        for i in range(n):
            LeftTrees = self.numTrees(i)
            RightTrees = self.numTrees(n - i - 1)
            Result += LeftTrees * RightTrees
        return Result

使用list缓存,用动态规划解决问题

class Solution:
    def numTrees(self, n: int) -> int:
        dp = [0 for _ in range(n+1)]
        dp[0] = 1
        dp[1] = 1
        for root in range(2,n+1):
            for left in range(0,root):
                dp[root] += dp[left]*dp[root-left-1]
        return dp[-1]