LeetCode 96. Unique Binary Search Trees

本文探讨了如何通过动态规划解决计算给定整数n时,可以构建出多少种独特的二叉搜索树的问题。详细解释了状态转移方程,并提供了Java实现的代码示例。

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

原题链接在这里:https://leetcode.com/problems/unique-binary-search-trees/

题目:

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

题解:

DP问题.

初始化, dp[0] = 1, dp[1] = 1. 当n=0时,返回1,只返回一个空树,当n=1时,返回1,只有一个节点的树.

状态转移,对于总共 i 个点, 它的返回值应该是对于每个点的不同左子树的个数dp[j] * 不同右子树的个数dp[i-1-j]的和. j在[0,i-1]区间内.  

答案dp[n].

Time Complexity: O(n^2). Space:O(n).

AC Java:

 1 class Solution {
 2     public int numTrees(int n) {
 3         int [] dp = new int[n+1];
 4         dp[0] = 1;
 5         dp[1] = 1;
 6         for(int i = 2; i<=n; i++){
 7             for(int j = 0; j<i; j++){
 8                 dp[i] += dp[j]*dp[i-j-1];
 9             }
10         }
11         return dp[n];
12     }
13 }

进阶版还有Unique Binary Search Trees II.

转载于:https://www.cnblogs.com/Dylan-Java-NYC/p/4824972.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值