leetcode -- 96. Unique Binary Search Trees

本文探讨了LeetCode上的经典题目——不同二叉搜索树(Unique Binary Search Trees),提供了两种AC代码实现,一种是动态规划解决方案,另一种是递归方法。动态规划解法通过迭代计算不同子树的数量,而递归解法则通过枚举根节点来求解左右子树的组合数。

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

题目描述

题目难度:Medium

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

Example:

Input: 3
Output: 5
Explanation:
Given n = 3, there are a total of 5 unique BST’s:
在这里插入图片描述

AC代码1

leetcode 上优秀的解法,带解释:
https://leetcode.com/problems/unique-binary-search-trees/discuss/31707/Fantastic-Clean-Java-DP-Solution-with-Detail-Explaination

public int numTrees(int n) {
    int [] dp = new int[n+1];
    dp[0]= 1;
    dp[1] = 1;
    for(int level = 2; level <=n; level++)
        for(int root = 1; root<=level; root++)
            dp[level] += dp[level-root]*dp[root-1];
    return dp[n];
}

AC代码2

leetcode 95题的拓展,参考:https://blog.youkuaiyun.com/tkzc_csk/article/details/88567857

class Solution {
    public int numTrees(int n) {
        if(n < 1) return 0;
        return numTrees(1, n);
    }
    
    private int numTrees(int left, int right){
        if(left > right) return 1;
        if(left == right) return 1;
        int res = 0;
        int leftNum = 0;
        int rightNum = 0;
        for(int i = left;i <= right;i++){
            leftNum = numTrees(left, i - 1);
            rightNum = numTrees(i + 1, right);
            res += leftNum * rightNum;
        }
        return res;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值