LeetCode 96. Unique Binary Search Trees

本文探讨了如何计算不同数量的节点所能构成的不同结构的二叉搜索树的数量,并通过递推方式给出了具体算法实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

For example,
Given n = 3, there are a total of 5 unique BST's.

   1         3     3      2      1
    \       /     /      / \      \
     3     2     1      1   3      2
    /     /       \                 \
   2     1         2                 3
分析:要形成二分查找树,可以选取一个根节点,然后它的左子树和右子树都要为二分查找树,根据递归的思想,可以归纳出一些规律:

nBST个数备注
01空树
11只有根结点
21x1+1x1=2根结点为1,右子树对应n = 1的情况
根结点为2,左子树对应也是n=1的情况
31x2+1x1+1x2=5根结点为1,右子树对应n = 2的情况
根结点为2,比其小的左子树只有一种情况,比其大的右子树只有一种情况,共只有1x1种情况
根结点为3,左子树对应n = 2的情况
41x5+1x2+1x2+1x5=14根结点为1,右子树对应n = 3的情况
根结点为2,左子树只有一种情况,右子树对应n = 2的情况,共1x2种情况
根结点为3,右子树只有一种情况,左子树对应n = 2的情况,共1x2种情况
根结点为4,左子树对应n = 3的情况

将每个 n 值对应的BST个数记录到一个数组count[]里,前两个我们知道
count[0] = 1;
count[1] = 1;
count[2] = count[0] * count[1] + count[1] * count[0] ;
count[3] = count[0] * conut[2] + count[1] * count[1] + count[2] * count[0];
……
count[n] = count[0] * count[n - 1] + count[1] * count[n - 2] + count[2] * count[n - 3] + … + count[n - 1] * count[0];
前辈的提醒下,知道这便是卡特兰数的定义。
代码:
public class Solution {
    public int numTrees(int n) {
        int[] count = new int[n + 1];
        count[0] = 1;
        count[1] = 1;
        for(int i = 2; i <= n; i++){
            for(int j = 0; j < i; j++){
                count[i] += count[j] * count[i - 1 - j];
            }
        }
        return count[n];
    }
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值