LeetCode刷题笔记 96. 不同的二叉搜索树

13 篇文章 0 订阅
6 篇文章 0 订阅

题目描述

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

总结

SDC1动态规划:

G(n) 是我们解决问题需要的函数。

G(n) 可以从F(i,n) 得到,而 F(i,n) 又会递归的依赖于G(n)。

首先,根据上一节中的思路,不同的二叉搜索树的总数 G(n)G(n),是对遍历所有 i (1 <= i <= n) 的 F(i, n)F(i,n) 之和。换而言之:
在这里插入图片描述

特别的,对于边界情况,当序列长度为 1 (只有根)或为 0 (空树)时,只有一种情况。亦即:

G(0)=1,G(1)=1

给定序列 1 … n,我们选出数字 i 作为根,则对于根 i 的不同二叉搜索树数量 F(i, n)F(i,n),是左右子树个数的笛卡尔积,如下图所示:

在这里插入图片描述

举例而言,F(3, 7)F(3,7),以 3 为根的不同二叉搜索树个数。为了以 3 为根从序列 [1, 2, 3, 4, 5, 6, 7] 构建二叉搜索树,我们需要从左子序列 [1, 2] 构建左子树,从右子序列 [4, 5, 6, 7] 构建右子树,然后将它们组合(即笛卡尔积)。
巧妙之处在于,我们可以将 [1,2] 构建不同左子树的数量表示为 G(2), 从 [4, 5, 6, 7]` 构建不同右子树的数量表示为 G(4)。这是由于 G(n) 和序列的内容无关,只和序列的长度有关。于是,F(3,7)=G(2)⋅G(4)。 概括而言,我们可以得到以下公式:

F(i,n)=G(i−1)⋅G(n−i)

将公式 (1),(2) 结合,可以得到 G(n) 的递归表达公式:

在这里插入图片描述

为了计算函数结果,我们从小到大计算,因为 G(n)G(n) 的值依赖于 G(0) … G(n-1)G(0)…G(n−1)。

SDC2:递归

SDC3:数学,卡塔兰数
在这里插入图片描述
在这里插入图片描述

Sample & Demo Code 1

class Solution {
    public int numTrees(int n) {
        int[] res = new int[n+1];
        res[0] = 1; res[1] = 1;
        
        for(int i = 2; i <= n; i++) {
            for(int j = 1; j <= i; j++) {
                res[i] += res[i-j]*res[j-1];
            }
        }
        return res[n];
    }
}

Sample & Demo Code 2

class Solution {
    public int numTrees(int n) {
        if(n == 0) return 0;
        return helper(1, n);
    }
    
    private int helper(int start, int end) {
        if(start >= end) return 1;
        
        int res = 0;
        for(int i = start; i <= end; i++)
            res += helper(start, i-1) * helper(i+1, end);
        return res;
    }
}

Sample & Demo Code 3

class Solution {
    public int numTrees(int n) {
        long res = 1;
        for(int i = 0; i < n; i++)      //注意这里 i = 0 !!!
            res = res * 2 * (2 * i + 1) / (i + 2);
        return (int) res;
    }
}

参考原文链接:
https://leetcode-cn.com/problems/unique-binary-search-trees/solution/bu-tong-de-er-cha-sou-suo-shu-by-leetcode/
https://leetcode-cn.com/problems/unique-binary-search-trees/solution/xiang-xi-tong-su-de-si-lu-fen-xi-duo-jie-fa-by-2-8/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值