LeetCode-96. Unique Binary Search Trees
来源:互联网 发布:windows 98 iso 编辑:程序博客网 时间:2024/06/01 08:50
题目: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
分析一波:
题目要求给定一个数字n,求出能包含1~n个值的二叉搜索树有几棵。
假设 f(i)代表数字i的二叉搜索树有几棵。
默认这些值升序排列并且当作一个个的节点。
n=1,可得到f(1)=1;
n=2, 可选择最左边的值当作根节点,那么最右边节点只能当作右子树,同理,最右节点当作根节点,最左节点当作左子树
即f(2)=f(1)+f(1)=2;
n=3,最左节点当作根节点,则剩下的两个节点就是n=2时的情况,中间节点当作根节点,则可得到 f(左节点的个数)*f(右节点的个数)[根据组合的知识],最右节点当作根节点,左边剩下的两个节点就是n=2时的情况。
f(3)=f(2)+f(1)*f(1)+f(2);
…
为n时的情况,
f(n)=f(n-1)+f(1)*f(n-2)+…+f(n-2)f(1)+f(n-1);
经本人查找资料,
此类题目与数学上的卡特兰数有密切联系。
以下是代码
public class UniqueBinarySearchTree { public int numTrees(int n) { int[] f=new int[n+1]; f[0]=f[1]=1; for(int i=2;i<=n;i++) { for(int j=1;j<=i;j++) { f[i]+=f[j-1]*f[i-j]; } } return f[n]; }}
题目:
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
分析一波:
题目要求给定一个数字n,求出能包含1~n个值的二叉搜索树有几棵。
假设 f(i)代表数字i的二叉搜索树有几棵。
默认这些值升序排列并且当作一个个的节点。
n=1,可得到f(1)=1;
n=2, 可选择最左边的值当作根节点,那么最右边节点只能当作右子树,同理,最右节点当作根节点,最左节点当作左子树
即f(2)=f(1)+f(1)=2;
n=3,最左节点当作根节点,则剩下的两个节点就是n=2时的情况,中间节点当作根节点,则可得到 f(左节点的个数)*f(右节点的个数)[根据组合的知识],最右节点当作根节点,左边剩下的两个节点就是n=2时的情况。
f(3)=f(2)+f(1)*f(1)+f(2);
…
为n时的情况,
f(n)=f(n-1)+f(1)*f(n-2)+…+f(n-2)f(1)+f(n-1);
经本人查找资料,
此类题目与数学上的卡特兰数有密切联系。
以下是代码
public class UniqueBinarySearchTree { public int numTrees(int n) { int[] f=new int[n+1]; f[0]=f[1]=1; for(int i=2;i<=n;i++) { for(int j=1;j<=i;j++) { f[i]+=f[j-1]*f[i-j]; } } return f[n]; }}
阅读全文
0 0
- LeetCode 96. Unique Binary Search Trees II
- [LeetCode]96.Unique Binary Search Trees
- 96. Unique Binary Search Trees Leetcode
- [Leetcode] 96. Unique Binary Search Trees
- LeetCode --- 96. Unique Binary Search Trees
- [leetcode] 96.Unique Binary Search Trees
- [leetcode] 96. Unique Binary Search Trees
- 96. Unique Binary Search Trees LeetCode
- <LeetCode OJ> 96. Unique Binary Search Trees
- [LeetCode]96. Unique Binary Search Trees
- [LeetCode]96. Unique Binary Search Trees
- LeetCode 96. Unique Binary Search Trees
- *LeetCode 96. Unique Binary Search Trees
- Leetcode 96. Unique Binary Search Trees
- LeetCode *** 96. Unique Binary Search Trees
- LeetCode 96. Unique Binary Search Trees
- LeetCode 96.Unique Binary Search Trees
- Leetcode:96. Unique Binary Search Trees
- 无线传感器网络定位算法
- IO Streams:格式化
- bzoj1070: [SCOI2007]修车(最小费用最大流)
- Spring的基本用法
- 10月7日 c语言编程 输入三个字符串,要求找出其中最大者
- LeetCode-96. Unique Binary Search Trees
- 百年孤独 结尾
- Python+Selenium WebDriver API:浏览器及元素的常用函数及变量整理总结
- 移植mavlink协议遇到的问题:future、pip3
- ACM 判定
- Rotate Image
- 判断单链表中是否有环,找到环的入口节点
- hdu 1532 Drainage Ditches
- 1051. 复数乘法 (15)