博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode] Unique Binary Search Trees
阅读量:6985 次
发布时间:2019-06-27

本文共 1064 字,大约阅读时间需要 3 分钟。

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

 

 

Hide Tags
   
 
思路:dp
 

如果集合为空,只有一种BST,即空树,

UniqueTrees[0] =1

如果集合仅有一个元素,只有一种BST,即为单个节点UniqueTrees[1] = 1

UniqueTrees[2] = UniqueTrees[0] * UniqueTrees[1]   (1为根的情况)+ UniqueTrees[1] * UniqueTrees[0]  (2为根的情况)。

再看一遍三个元素的数组,可以发现BST的取值方式如下:

UniqueTrees[3] = UniqueTrees[0]*UniqueTrees[2]  (1为根的情况)

+ UniqueTrees[1]*UniqueTrees[1]  (2为根的情况)

+ UniqueTrees[2]*UniqueTrees[0]  (3为根的情况)

所以,由此观察,可以得出UniqueTrees的递推公式为UniqueTrees[i] = ∑ UniqueTrees[0...k] * [i-1-k]     k取值范围 0<= k <=(i-1)

 

class Solution {    public:        int numTrees(int n) {            int *num = new int[n+1];            num[0] = 1;            num[1] = 1;            int tmp = 0;            for(int i =2; i <=n; i++)            {                   tmp = 0;                for(int j= 0; j 

 

转载地址:http://cbtpl.baihongyu.com/

你可能感兴趣的文章
Java-集合的简单介绍
查看>>
分布式架构发展
查看>>
针对不同的系统的宏定义
查看>>
Spring Boot + Vue 前后端分离,两种文件上传方式总结
查看>>
第一次搭建阿里云服务器
查看>>
java 文件存储
查看>>
Android build.gradle 获取Git 仓库数据
查看>>
十分钟熟练Dockerfile指令
查看>>
ES6新特征总结与介绍——声明与表达式
查看>>
python3实现抓取网页资源的 N 种方法(内附200GPython学习资料)
查看>>
自定义网络请求框架
查看>>
Unity(射线)
查看>>
阿里云媒体转码MTS使用教程
查看>>
shell常见的文件属性检查
查看>>
年度最期待游戏废土2登陆Linux
查看>>
CA knowledge study
查看>>
linux目录结构简析
查看>>
VMware ESXi部署OVF模板
查看>>
2上的svn部署
查看>>
《***测试实践指南》D03
查看>>