[LeetCode] 95. Unique Binary Search Trees II

Gemini 2.5 Pro国内免魔法直连教程:5分钟搞定专业级PPT图表(附折线图/柱状图案例) 本文详细介绍了如何利用Gemini 2.5 Pro快速生成专业级PPT图表,包括折线图和柱状图等常见商业图表。通过自然语言交互和智能图表生成功能,用户可以在5分钟内完成数据可视化,大幅提升工作效率。文章还提供了实战案例和高级技巧,帮助用户轻松应对各种商业场景需求。 阅读详情

Unique Binary Search Trees II

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

Input: 3
Output:
[
[1,null,3,2],
[3,2,null,1],
[3,1,null,null,2],
[2,1,3],
[1,null,2,null,3]
]
Explanation:
The above output corresponds to the 5 unique BST’s shown below:
1
\
3
/
2 等等

解析

递归构建二叉树,如果以 i 为根节点,那么其左子树由[1, i - 1]构成,右子树由[i + 1, n] 构成。要构建包含1到n的二叉搜索树,只需遍历1到n中的数作为根节点,以i为界将数列分为左右两部分,小于i的数作为左子树,大于i的数作为右子树,使用两重循环将左右子树所有可能的组合链接到以i为根节点的节点上。
例子:
举一个简单的数据验证下,以[1, 2, 3]为例,调用堆栈图如下所示:
helper(1,3)
[leftTree]: helper(1, 0) ==> return NULL
—loop i = 2—
[rightTree]: helper(2, 3)
[leftTree]: helper(2,1) ==> return NULL
[rightTree]: helper(3,3) ==> return node(3)
[for loop]: ==> return (2->3)
—loop i = 3—
[leftTree]: helper(2,2) ==> return node(2)
[rightTree]: helper(4,3) ==> return NULL
[for loop]: ==> return (3->2)

代码

class Solution {
public:
    vector<TreeNode*> generateTrees(int n) {
        if(n == 0)
            return {};
        return helper(1,n);
    }

    vector<TreeNode* > helper(int start, int end){
        vector<TreeNode *> result;
        if(start > end){
            result.push_back(NULL);
            return result;
        }
        for(int i=start; i <= end;i++){
            vector<TreeNode* > lefttree = helper(start, i-1);
            vector<TreeNode* > righttree = helper(i+1, end);
            for(int j=0; j < lefttree.size(); j++){
                for(int k=0; k < righttree.size(); k++){
                    TreeNode* root = new TreeNode(i);
                    root->left = lefttree[j];
                    root->right = righttree[k];
                    result.push_back(root);
                }
            }
        }
        return result;
    }
};

上述代码需要大量拷贝,使用指针存储变量,代码如下:

class Solution {
public:
    vector<TreeNode*> generateTrees(int n) {
        if(n == 0)
            return {};
        return *helper(1,n);
    }

    vector<TreeNode* > *helper(int start, int end){
        vector<TreeNode *> *result = new vector<TreeNode*>();
        if(start > end){
            result->push_back(NULL);
            return result;
        }
        for(int i=start; i <= end;i++){
            vector<TreeNode* > *lefttree = helper(start, i-1);
            vector<TreeNode* > *righttree = helper(i+1, end);
            for(int j=0; j < lefttree->size(); j++){
                for(int k=0; k < righttree->size(); k++){
                    TreeNode* root = new TreeNode(i);
                    root->left = (*lefttree)[j];
                    root->right = (*righttree)[k];
                    result->push_back(root);
                }
            }
        }
        return result;
    }
};

参考

https://www.kancloud.cn/kancloud/data-structure-and-algorithm-notes/73055
http://www.cnblogs.com/grandyang/p/4301096.html

Google Cameraserver 看门狗CameraServiceWatchdog超时crash原理分析 本文分析了Android CameraServiceWatchdog机制的工作原理。该看门狗用于监控相机服务关键操作(如close、flush)的超时情况,通过定时器线程检测阻塞问题。文章详细讲解了Watchdog的初始化流程、使能方式、内部定时器机制(默认周期100ms,650次循环触发超时),并提供了configureStreams阶段的客制化实现方案。当检测到超时,Watchdog会触发abort生成tombstone日志,便于调试分析。 阅读详情

相关推荐

雷电模拟器+Auto.js避坑指南:用桥接模式解决PC与模拟器连接超时问题

本文详细解析了雷电模拟器与Auto.js联调中的桥接模式应用,解决PC与模拟器连接超时问题。通过桥接模式配置、高频故障排查及多开环境下的高阶配置,提升开发效率与稳定性,特别适合需要稳定网络连接的Auto.js开发者。

weixin_28836989的博客 632

LeetCode95. Unique Binary Search Trees II

所有可能的BST

grllery的博客 462

《深入浅出强化学习原理入门》学习笔记(三)机器人找金币应用实例

《深入浅出强化学习原理入门》学习笔记(三)MDP应用实例

lxs3213196的博客 3187

LeetCode 95. Unique Binary Search Trees II

Description https://leetcode.com/problems/unique-binary-search-trees-ii/ 给定n,生成所有结构上唯一的二叉搜索树,并返回所有这些树的root。 Solving Ideas 与Unique Binary Search Trees类似,不同的是,这里需要构造出所有结构上唯一的BST 实现起来比较简单就是使用 递归 的方法,遍历所有...

wylu 317

sql server安装并SSMS连接

  SQL Server是一种广泛应用于网络业务数据处理的关系型数据库管理系统。SQL Server 2016是微软公司研发的新一代旗舰级数据库和分析平台,突出高级分析和丰富可视化,并融合了关键创新功能。其可提供对企业基础架构最高级别的支持,专门针对关键业务应用的多种功能与解决方案提供最高级别的可用性,并提供更多、更全面的功能以满足不同人群对数据的需求,包括支持来自不同网络环境的数据交互、全面的自助分析等创新功能。百度搜索sql server,在官网下载 地址是:SQL Server 下载| Microso

jiankang66的博客 5184

商品评论中的实体情感分析

在之前的文章中我已经将商品评论中的评价实体,也就是特征(feature)给挖掘出来了,我看了一下,挖掘的效果还是不错的。原文链接:http://blog.csdn.net/chixujohnny/article/details/52794685 下面一步要做的是施加情感因子,也就是说,要将人们评论时候所连带的感情程度施加一下。这项任务的归类应该是情感分析技术。 目前该类问题的情感分析技

chixujohnny 7971

leetcode 95. Unique Binary Search Trees II | 96. Unique Binary Search Trees

95. Unique Binary Search Trees II https://leetcode.com/problems/unique-binary-search-trees-ii/ 题解 题是好题,可惜我自己想不出来,后来偷看了答案。 难点在于在何处进行 list.add(root);,以及在修改树的形状时候,如何实现所谓的“深拷贝”,而不让树与树之间相互影响。 /** * Definition for a binary tree node. * public class TreeNode {

寒泉 4万+

Zemax实战:手把手教你设计一个40倍、NA0.65的显微物镜(附初始结构文件)

本文详细介绍了使用Zemax设计40倍、NA0.65显微物镜的完整流程,从初始结构搭建到优化验证,涵盖光学设计的关键技巧和实战经验。通过分阶段优化策略和公差分析,帮助工程师快速掌握高倍显微物镜的设计方法,提升光学系统性能。

weixin_42525369的博客 343

LeetCode力扣之95. Unique Binary Search Trees II

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

LeeWei 296

AUTOSAR内存篇 -内存驱动(Mem)

Mem驱动程序的task是基于底层内存设备技术的物理分段的低级内存访问。Mem驱动程序的API与内存设备技术无关,因此向存储器访问模块上层提供了与存储器设备无关的接口。所有高级功能(如跨段操作)都由内存访问模块处理,以尽可能降低Mem驱动器的复杂性和占用空间。Mem驱动API命名、类型定义和文件命名规则都遵循标准的AUTUSAR BSW模块实现。服务Mem_Init初始化Mem驱动的内部状态,并设置Mem驱动Job处理状态到MEM_JOB_OK。

IOT2017的博客 713

从0到全栈:C#/.NET/.NET Core终极学习路线——2025年开发者必修的12个阶段与30个实战项目

【代码】从0到全栈:C#/.NET/.NET Core终极学习路线——2024年开发者必修的12个阶段与30个实战项目。

墨夶的博客 2042

Leetcode 95 Unique Binary Search Trees II

给出n,生成所有存储1-n共n个数的结构上不重复的二叉查找树。

(ง •̀_•́)ง 589

深度学习工具包 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 95: Unique Binary Search Trees II

问题描述 思路 https://leetcode.wang/leetCode-95-Unique-Binary-Search-TreesII.html#%E8%A7%A3%E6%B3%95%E5%9B%9B-%E5%8A%A8%E6%80%81%E8%A7%84%E5%88%92-2 递归 二叉树搜索树的性质:左子树的所有值小于根节点,右子树的所有值大于根节点。 所以如果求 1…n 的所有可能,...

zero 194

VC中sqlite的使用

在VC中对sqlite的使用,实现数据库大批数据的快速插入,读取数据库中的数据在ListCtrl中显示

华为的C语言编程规范.pdf

华为技术有限公司内部技术规范。本规范制定了编写C语言程序的基本原则、规则和建议。从代码的清晰、简洁、可测试、安全、程序效率、可移植各个方面对C语言编程作出了具体指导。

( Leetcode 95 ) Unique Binary Search Trees II

题目:Unique Binary Search Trees II 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

willduan的博客 6566

LeetCode95—Unique Binary Search Trees II

LeetCode95—Unique Binary Search Trees II 分治法求解结构不同BST(查找二叉树)

上善若水 542

leetcode【95】Unique Binary Search Trees II

问题描述 Given an integern, generate all structurally uniqueBST's(binary search trees) that store values 1 ...n. 大概意思就是给定一个正整数n,然后写出所有可能的二叉树。 解决方案 递归方法: 二叉树由左子树和右子树组成,那么左子树和右子树就是子问题。递归过程中每次选一个点...

fanyuwgy的博客 169

Leetcode 95. Unique Binary Search Trees II

Leetcode 95. Unique Binary Search Trees II Given an integer n, generate all structurally unique BST’s (binary search trees) that store values 1 … n. Example: Input: 3 Output: [ [1,null,3,2], [3,2,null...

fengran_mark的博客 166

Leetcode95. Unique Binary Search Trees II

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

Barbie_1229的博客 456

[leetcode] 95. Unique Binary Search Trees II 解题报告

题目链接:https://leetcode.com/problems/unique-binary-search-trees-ii/ Given n, generate all structurally unique BST's (binary search trees) that store values 1...n. For example, Given n = 3, your

小榕流光的专栏 834

leetcode[95] Unique Binary Search Trees II

和上一题Unique Binary Search Trees一样,这里是要记录所有的可能。存在树里面。 这题还是有点难的,我拿了笔写了前几个,推敲了一下,发现如果和上一题一样,存前面的值计算后面的的话会非常复杂,且可能涉及到给一颗数的所有节点加某个值。最终还是放弃用这个方法。 可行的二叉查找树的数量是相应的卡特兰数,不是一个多项式时间的数量级,所以我们要求解所有的树,自然是不能多项...

97

LeetCode --- 95. Unique Binary Search Trees II

题目链接:Unique Binary Search Trees II Given 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 B

makuiyu的专栏 1099

leetcode-95. Unique Binary Search Trees II

leetcode-95. Unique Binary Search Trees II题目: 这题第二遍做还是没做出来,我总是想怎么用动态规划区解,主要还是偷看了tag。想在n-1的基础上找n很久都没找到。这里实际上并不能算是DP算法。应该还是DFS方法或者分治算法。 思路就是针对1-n之间的每个i去找其左子节点和右子节点,分别形成TreeNode数组然后在数组里的互相匹配构成上一层的数组。算法设计的非常漂亮。

千念飞羽的专栏 656

【Leetcode】95. Unique Binary Search Trees II

题目地址: https://leetcode.com/problems/unique-binary-search-trees-ii/ 返回所有节点值恰好是1∼n1\sim n1∼n的nnn个节点的二叉搜索树的树根。 思路是递归。开一个函数f(l,r)f(l,r)f(l,r)返回所有值恰好是l∼rl \sim rl∼r的二叉搜索树的树根,那么对于树根为xxx的二叉搜索树,它的左子树的可能取值就是f(1,x−1)f(1,x-1)f(1,x−1),右子树可能的取值就是f(x+1,r)f(x+1,r)f(x+1,r

数学、算法爱好者的博客 178
上一篇: [LeetCode] 96. Unique Binary Search Trees
下一篇: [LeetCode] 98. Validate Binary Search Tree
Peng_maple
博客等级 码龄10年 0粉丝 79原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值