首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >​LeetCode刷题实战96:不同的二叉搜索树

​LeetCode刷题实战96:不同的二叉搜索树

作者头像
程序员小猿
发布2021-01-19 17:14:00
发布2021-01-19 17:14:00
2820
举报
文章被收录于专栏:程序IT圈程序IT圈

今天和大家聊的问题叫做 不同的二叉搜索树,我们先来看题面:

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

Given n, how many structurally unique BST's (binary search trees) that store values 1 ... n?

题意

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

样例

解题

递归子问题

假设 n 个节点存在二叉排序树的个数是 G (n),令 f(i) 为以 i 为根的二叉搜索树的个数,则

G(n)=f(1)+f(2)+f(3)+f(4)+...+f(n),

f(i)=G(i−1)∗G(n−i)

代码语言:javascript
复制
class Solution {
    public int numTrees(int n) {
        if (n == 0 || n == 1) return 1;
        int res = 0;
        for (int i = 1; i <= n; i++) {
            res += numTrees(i - 1) * numTrees(n - i);
        }
        return res;
    }
}

动态规划

从dp[0],dp[1]开始逐渐向后扩大

代码语言:javascript
复制
public class Solution {
    public int numTrees(int n) {
        int[] dp = new int[n + 1];
        dp[0] = dp[1] = 1;
        for (int i = 2; i <= n; i++) {
            for (int j = 1; j <= i; j++) {
                dp[i] += dp[j - 1] * dp[i - j];
            }
        }
        return dp[n];
    }
}

好了,今天的文章就到这里。

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2020-11-14,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 程序员小猿 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题意
  • 解题
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档