力扣 96. 不同的二叉搜索树

该博客探讨了如何计算具有给定节点数n的不同互不相同节点的二叉搜索树的总数。通过递归方法和备忘录技术解决这个问题,避免重复计算。示例展示了当n为3和1时的输出,并提供了Python和Java两种实现方式。
摘要由CSDN通过智能技术生成
题目

给你一个整数 n ,求恰由 n 个节点组成且节点值从 1 到 n 互不相同的 二叉搜索树 有多少种?返回满足题意的二叉搜索树的种数。

示例

在这里插入图片描述

输入:n = 3
输出:5

输入:n = 1
输出:1

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/unique-binary-search-trees
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

方法1

【1,2,3,4,5】,若3为根结点,有2X2=4种组合。定义一个count方法

当lo > hi闭区间[lo, hi]肯定是个空区间,也就对应着空节点 null,虽然是空节点,但是也是一种情况,所以要返回 1 而不能返回 0。

备忘录为n+1,是因为计算1-n。

备忘录memo,消除重叠子问题。

Python实现
class Solution:
    def numTrees(self, n: int) -> int:
        #备忘录,初始值都为0
        memo=[[0]*(n+1) for i in range(n+1)]

        def count(low,high):
        	//空结点返回1
            if low>high: return 1
            if memo[low][high]!=0: return memo[low][high]
			
			//递归计算每个数做结点的可能性
            res=0
            for i in range(low,high+1):
                left=int(count(low,i-1))
                right=int(count(i+1,high))
                res+=left*right
            memo[low][high]=res
            return res
        return count(1,n)

在这里插入图片描述

Java实现
class Solution {
    // 存储i-j的数构成的BST数目
    int[][] nums;
    public int numTrees(int n) {
        nums = new int[n + 1][n + 1];
        
        return count(1, n);
    }

    public int count(int low, int high) {
        if (low > high) {
            return 1;
        }
        // 检查nums是否存储数目
        if (nums[low][high] != 0) {
            return nums[low][high];
        }

        // 计数
        int num = 0;
        for (int i = low; i <= high; i++) {
            int left = count(low, i - 1);
            int right = count(i + 1, high);

            num += left * right;
        }
        nums[low][high] = num;

        return num;
    }
}

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值