Leetcode_med 96. 不同的二叉搜索树

描述

给定一个整数 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]
全部评论

相关推荐

昨天 18:30
门头沟学院 Java
据说名字越长别人越关注你的昵称我觉得我要被关注了:你问问这里面有多少是正经候选人,而不是乱打招呼的
点赞 评论 收藏
分享
企业都这么缺人了吗?缺人为什么还给白菜价!
真起不了响亮的名字:我给你出个主意,把公司报出来,让牛友去投,岂不美哉
点赞 评论 收藏
分享
05-09 13:22
门头沟学院 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务