LC-96.不同的二叉搜索树

思路:

此题的难点是找出递推公式!

首先要知道什么是二叉搜索树,其次,要将n=2的二叉搜索树画出来,然后发现其中的规律。

在n=3的情况下:

当头节点是1时,其左右孩子为n=2时的二叉搜索树的布局;

当头节点是2时,其左右孩子是n=1的二叉搜索树的布局;

当头结点是3时,其左右孩子是n=2的二叉搜索树的布局.

不难发现:

dp[3] = dp[2] * dp[0] + dp[1] * dp[1] + dp[0] * dp[2]

以上就可以知道该dp数组的递推公式为:

dp[i] += dp[j]*dp[i-1-j];

那就开始递归五部曲

1.定义dp数组

dp[i] :表示数字i有的dp[i]种二叉搜索树的排序。

2.递推公式

dp[i] += dp[j]*dp[i-1-j];

3.初始化dp数组

dp[0]=1;

dp[1]=1;

4.遍历顺序

由递推公式可以知道,dp[i]与其前面的数据有关,所以就是正序遍历。

5.打印dp数组

由dp数组的定义可以知道,整数n的二叉搜索树个数为dp[n];所以最后输出dp[n],定义dp数组的长度是定义为n+1。

代码

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

    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Sure! Here's your code with comments added: ```matlab F = zeros(length(z), 1); % Initialize the F vector with zeros for i = 1:length(z) % Define the Phi function using anonymous function Phi = @(theta, R, r) (z(i) + lc - lm) .* r.R .(R - r.sin(theta)) ./ ... ((R.^2 + r.^2 - 2*R.*r.*sin(theta)).sqrt(R.^2 + r.^2 + (z(i) + lc - lm).^2 - 2*R.*r.*sin(theta))) + ... (z(i) - lc + lm) .* r.R .(R - r.sin(theta)) ./ ... ((R.^2 + r.^2 - 2*R.*r.*sin(theta)).sqrt(R.^2 + r.^2 + (z(i) - lc + lm).^2 - 2*R.*r.*sin(theta))) + ... (z(i) + lc + lm) .* r.R .(R - r.sin(theta)) ./ ... ((R.^2 + r.^2 - 2*R.*r.*sin(theta)).sqrt(R.^2 + r.^2 + (z(i) + lc + lm).^2 - 2*R.*r.*sin(theta))) + ... (z(i) - lc - lm) .* r.R .(R - r.sin(theta)) ./ ... ((R.^2 + r.^2 - 2*R.*r.sin(theta)).sqrt(R.^2 + r.^2 + (z(i) - lc - lm).^2 - 2*R.*r.sin(theta))); % Calculate the value of F(i) using the integral3 function F(i) = BrNI / (4 * lc * (Rc - rc)) * integral3(Phi, 0, 2*pi, rc, Rc, rm, Rm); end ``` This code calculates the values of the vector `F` using a loop. The `Phi` function is defined as an anonymous function that takes `theta`, `R`, and `r` as input parameters. It performs a series of calculations and returns a value. The integral of `Phi` is then calculated using the `integral3` function. The result is stored in the corresponding element of the `F` vector. Please note that I have made some assumptions about the variables and functions used in your code since I don't have the complete context. Feel free to modify or clarify anything as needed.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

想进阿里的小菜鸡

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值