96. Unique Binary Search Trees

本文介绍了一种生成所有结构上唯一的二叉搜索树(BST)的算法,这些BST存储从1到n的值。通过递归地选择根节点并确定左右子树的元素数量来解决该问题。给出的代码实现了这一算法,并展示了当n为3时,可以生成5棵不同的二叉搜索树。

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

Given an integer n, generate all structurally unique BST's (binary search trees) that store values 1...n.

For example,
Given n = 3, your program should return all 5 unique BST's shown below.

   1         3     3      2      1
    \       /     /      / \      \
     3     2     1      1   3      2
    /     /       \                 \
   2     1         2                 3

The idea is Suppose we know the solution from 1 to n-1, and we want to know about n;

F(n) = 0;

We could choose a number X from 1 to n to be the root, and all the numbers in the left subtree i < X and in the right tree i > X

There are (i - 1) number in the left tree and (n - i) number in the right tree.

F(n) += F(i - 1) * F(n - i) for i from 1 to N 

Code:

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


in the above code k stands for how many number in the left tree and (i - k - 1) stands for how many number in the right tree. 





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值