【卡塔兰数】LeetCode 96. Unique Binary Search Trees

升降机SEW MOVIDRIVE变频器设置 选择PO1 第2,3,9,13 位,点击“SendPA”Start reference,编码器反馈值为0(PI2/3 Actual position=0)提示:传送参考位置前请断开变频器安全24V电源,否则会弹出禁止修改提示框;提示:做这一步时,如果出现电机不能转动,或产生报警不能通过编码器匹配。下载配置的参数,提示:下载参数需要断开变频器的安全24V电源。编码器匹配通过后点击下一步,进入下图画面传送参考位置。1电机不能转动:a可能是由于变频器的安全24V未给。点击2.SEW总线扩展定位,定位块设置。 阅读详情

LeetCode 96. Unique Binary Search Trees

本博客转载自:http://www.cnblogs.com/grandyang/p/4299608.html
Solution1:
这道题实际上是Catalan Number卡塔兰数的一个例子。

                    1                        n = 1

                2        1                   n = 2
               /          \
              1            2

   1         3     3      2      1           n = 3
    \       /     /      / \      \
     3     2     1      1   3      2
    /     /       \                 \
   2     1         2                 3

就跟斐波那契数列一样,我们把n = 0 时赋为1,因为空树也算一种二叉搜索树,那么n = 1时的情况可以看做是其左子树个数乘以右子树的个数,左右字数都是空树,所以1乘1还是1。那么n = 2时,由于1和2都可以为跟,分别算出来,再把它们加起来即可。n = 2的情况可由下面式子算出:
当数组为1,2,3,…,n时,基于以下原则构建的BST树具有【唯一性:以i为根结点的树,其左子树由[1, i-1]构成,其右子树由[i+1, n]构成】(参考自《leetcode-cpp 答案》)。
dp[2] = dp[0] * dp[1]   (1为根的情况)
   + dp[1] * dp[0]   (2为根的情况)
上面递归式的含义是:
2个元素组成的数的个数 = 左子树0个元素 * 右子树1个元素 (1为根的情况)
+ 左子树1个元素 * 右子树0个元素 (2为根的情况)
同理可写出 n = 3 的计算方法:
dp[3] = dp[0] * dp[2]   (1为根的情况)
    + dp[1] * dp[1]   (2为根的情况)
   + dp[2] * dp[0]   (3为根的情况)
上面递归式的含义是:
3个元素组成的数的个数 = 左子树0个元素 * 右子树2个元素 (1为根的情况)
+ 左子树1个元素 * 右子树1个元素 (2为根的情况)
+ 左子树2个元素 * 右子树0个元素 (3为根的情况)
由此可以得出卡塔兰数列的递推式为:
这里写图片描述
时间复杂度 O(n2) O ( n 2 ) ,空间复杂度 O(n) O ( n )

class Solution {
public:
    int numTrees(int n) {
        vector<int> dp(n + 1, 0);
        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 - j - 1];
            }
        }
        return dp[n];
    }
};
MacOS蓝牙连接疑难杂症:从基础排查到高级修复全攻略 本文提供了一份全面的MacOS蓝牙故障排查与修复指南。从基础的菜单栏检查、终端命令诊断,到软/硬重启蓝牙服务、删除配置文件,再到使用blueutil工具、重置NVRAM等高级方法,系统性地解决了蓝牙无法连接、连接不稳定等常见问题。最后还分享了环境干扰排查、预防措施及硬件故障自检方法,帮助用户彻底解决Mac蓝牙连接难题。 阅读详情

相关推荐

UE4_后期处理六—夜视仪、扫描线

观察下面一组蓝图节点的效果:当把角色的自定义深度通道开启:画面效果如图:这样我们就得到了一个这样的黑白蒙版。

Growthofnotes的博客 1734

leetcode(96)不同的二叉搜索树——卡塔兰数

题目描述 给定一个整数 n,求以 1 … n 为节点组成的二叉搜索树有多少种? 示例: 输入: 3 输出: 5 解释: 给定 n = 3, 一共有 5 种不同结构的二叉搜索树: 1 3 3 2 1 \ / / / \ \ 3 2 1 1 3 2 ...

辰巳X4 527

别再为Word转PDF表格变形发愁了!Aspose.Words for Java 19.5 保姆级避坑指南

本文详细介绍了使用Aspose.Words for Java 19.5解决Word转PDF时表格变形问题的完整方案。从格式转换原理到实战技巧,涵盖固定表格宽度、禁用自动调整、强制文本换行等核心方法,并提供高级场景应对策略和性能优化建议,帮助开发者高效处理复杂文档转换需求。

weixin_28702105的博客 267

LeetCode96: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 \

3452

实战指南:基于汇川PLC与EtherNET/IP的无线以太网通信配置详解

本文提供了一份详细的实战指南,讲解如何配置汇川PLC基于EtherNET/IP协议的无线以太网通信。通过硬件选型(如达泰DTD419MB模块)、软件设置(使用AutoShop配置IP与I/O映射)及通信测试,实现PLC间稳定、灵活的数据交换,有效解决工业现场布线难题,提升部署与维护效率。

lake5的博客 616

数字后端实现Innovus教程之手把手教你N种高亮timing path和clock tree方法

数字IC后端设计实现Innovus教程之手把手教你N种高亮timing path和clock tree方法

weixin_37584728的博客 3604

【leetcode】96. Unique Binary Search Trees

96.Unique Binary Search Trees Givenn, how many structurally uniqueBST's(binary search trees) that store values 1 ...n? Example: Input: 3 Output: 5 Explanation: Given n = 3, there are a total ...

lemonade13的博客 235

RK3568 HDMI输出调试:分辨率切换与EDID解析

厂商信息(Vendor ID)显示器型号(Product ID)支持的分辨率列表色彩特性音频支持情况检查项方法HPD 信号EDID 读取当前模式TMDS 时钟PHY 状态。

小灰灰的博客 1493

[C++]LeetCode: 53 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

cindy_niu的专栏 1265

数据结构课程设计C/C++版--美团餐馆预定信息的管理与分析 5 6

第5关:注销个人信息。

m0_62222486的博客 2134

天气预测模型:基于时间序列分析的数学建模与实战案例

目录引言时间序列分析介绍使用Matlab进行天气预测实战案例:天气预测结论天气预测一直是气象学和相关领域的重要研究问题之一。数学建模是进行天气预测的有效方法之一,其中时间序列分析是常用的技术。在本篇博客中,我们将介绍时间序列分析的基本原理,演示如何使用Matlab进行模型建立和预测,并通过一个实战案例来展示模型的应用和分析。时间序列分析是一种用于分析和预测时间序列数据的统计方法。天气数据通常具有时间依赖性和随机性,因此时间序列分析可以帮助我们了解天气的变化趋势和规律,并提供对未来天气的预测。时间序列分析通常

YOLO 1547

96. Unique Binary Search Trees

Arithmetic Slices 题目描述 leetcode.64 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...

天台一只小蜗牛 163

YOLOv11涨点改进 | 首发全网创新、主干改进篇 | AAAI 2026 | PartialNet 主干让 YOLOv11 更加强大!引入部分通道机制 和 部分注意力卷积,全方面提升了模型的性能

本文提出PartialNet主干网络改进YOLOv11的方法,通过部分通道机制(PCM)和部分注意力卷积(PATConv)提升模型效率。PartialNet将特征图通道拆分并应用不同操作,显著减少计算量和内存占用。主要创新包括:1)部分通道机制实现计算优化;2)三种注意力模块(PATch/PATsp/PATsf)增强特征提取;3)动态部分卷积(DPConv)自适应调整计算复杂度。文章详细提供了代码实现和YOLOv11集成方法。

Ai缝合怪、助力小伙伴高效发论文 269

LeetCode | Unique Binary Search Trees

参考博文:http://fisherlei.blogspot.sg/2013/03/leetcode-unique-binary-search-trees.html题目Given n, how many structurally unique BST’s (binary search trees) that store values 1…n?For example, Given n = 3, th

益达的小作坊 431

C# WinForm 基于DirectShow.dll编写的程序,可边预览边保存视频,音频和图片

基于微软的DirectShow.dll的二次开发1.自动识别连接的摄像头跟麦克风且可以对其进行选择(默认选中第一个)2.可录制wmv和avi两种格式的视频并且都带有音频,avi可以录制的分辨率和帧数进行选择,wmv默认进行了淸晰度优化如不喜欢可去除代码中有相关提示3.可在预览点开之后进行拍照,也可边录制视频边拍照4.添加了视频和音频的压缩功能(酌情使用)这次二次开发发现C#对DirectShow的相关信息太少,这次做完也不敢藏私共享出来,还望大家指正

数学建模模型总结

这是本人在两年内准备参加数学建模竞赛搜集到的模型资料,已经经过了本人的筛选和整理,希望能够对准备参加数学建模竞赛的学弟学妹们提供一些帮助!

leetcode 96 Unique Binary Search Trees

原题链接:Unique Binary Search Trees - LeetCode 题目 Given an integer n, return *the number of structurally unique **BST’*s (binary search trees) which has exactly n nodes of unique values from 1 to n. Example 1: Input: n = 3 Output: 5 Example 2: Input: n = 1 Ou

mofei 281

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

LeetCode Top 100 Liked Questions 96. Unique Binary Search Trees (Java版; Medium)

welcome to my blog LeetCode Top 100 Liked Questions 96. Unique Binary Search Trees (Java版; Medium) 题目描述 Given n, how many structurally unique BST's (binary search trees) that store values 1 ...n? Exa...

littlehaes的博客 201

IDEA的使用指南

IDEA基于java的使用手册,可以最快速的上手,在使用中不断的丰富自己的使用技巧.

LeetCode——Unique Binary Search Trees

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: 1 3 ...

sinat_22994595的博客 201

[Leetcode]96. Unique Binary Search Trees

这是Leetcode第96题,给定一个 \(n\),求共有多少种不同的 \(BST\)(二叉搜索树)。 这道题实际上是 卡塔兰数 (Catalan Numbe) 的一个例子,也是很经典的一个问题了。下面,了解一下什么是卡特兰数以及它的性质。 卡特兰数是一种经典的组合数,经常出现在各种计算中,其前几项为 : 1, 2, 5, 14, 42, 132, 429, 1430, 4862, 16...

weixin_30432179的博客 173

LeetCode:Unique Binary Search Trees(二叉查找树)

一、BST特点 若任意节点的左子树不空,则左子树上所有结点的值均小于或等于它的根结点的值; 任意节点的右子树不空,则右子树上所有结点的值均大于它的根结点的值; 任意节点的左、右子树也分别为二叉查找树。 二、题目Given n, how many structurally unique BST’s (binary search trees) that store values 1…n? For ex

Lin_drink_caffe的博客 393

LeetCode—96. Unique Binary Search Trees

LeetCode—96. Unique Binary Search Trees 题目 https://leetcode.com/problems/unique-binary-search-trees/ 一个有n个节点的二叉搜索树,有多少种不同的结构。 思路及解法 二叉搜索树:对于任意一个节点root,其左子树中的元素小于root,其右子树中的元素大于root。二叉搜索树的中序遍历是非递减的。 解...

pnnngchg的博客 218

leetcode-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

sinat_24520925的专栏 693

leetcode------Unique Binary Search Trees

标题: Unique Binary Search Trees 通过率: 37.0% 难度: 中等 Givenn, how many structurally uniqueBST's(binary search trees) that store values 1...n? For example,Givenn= 3, the...

djiutyih440865的博客 106

LeetCode 96.Unique Binary Search Trees

LeetCode 96.Unique Binary Search TreesGiven 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

编程小白的进阶之路 224

[LeetCode] Unique Binary Search Trees 独一无二的二叉搜索树

题目 Given&amp;amp;nbsp;n, how many structurally unique&amp;amp;nbsp;BST’s&amp;amp;nbsp;(binary search trees) that store values 1…n? For example,Given&amp;amp;nbsp;n&amp;amp;nbsp;= 3, the

Britesun的博客 190

[LeetCode] 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

518

leetcode question 96: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 \...

csdn609387481的博客 201
上一篇: LeetCode 106. Construct Binary Tree from Inorder and Postorder Traversal
下一篇: LeetCode 104. Maximum Depth of Binary Tree
Allenlzcoder
博客等级 码龄10年 925粉丝 512原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值