LeetCode Unique Binary Search Trees
来源:互联网 发布:淘宝网购如何退货 编辑:程序博客网 时间:2024/05/20 06:28
题目
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
数1~n可以组成的合法的二叉树数量。
注意到:每i个不同的数可以组成的二叉树数量是相同的。
递推公式:
第1~m时的合法数数量n(m)=n(0)*n(m-1)+n(1)*n(m-2)+...n(m-1)*n(0)。
代码:
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: int numTrees(int n) {if(n==0)return 0;vector<int> solution;//表示1到n的各个数的二叉树数量solution.push_back(1); for(int i=1;i<=n;i++)//递推 { solution.push_back(0);for(int j=0;j<i;j++)solution[i]+=solution[j]*solution[i-j-1];}return solution[n]; }};
0 0
- LeetCode: Unique Binary Search Trees
- LeetCode : Unique Binary Search Trees
- [Leetcode] Unique Binary Search Trees
- [LeetCode]Unique Binary Search Trees
- LeetCode Unique Binary Search Trees
- Leetcode: Unique Binary Search Trees
- LeetCode-Unique Binary Search Trees
- [leetcode] Unique Binary Search Trees
- LeetCode - Unique Binary Search Trees
- [LeetCode] Unique Binary Search Trees
- 【Leetcode】Unique Binary Search Trees
- Leetcode: Unique Binary Search Trees
- 【LeetCode】Unique Binary Search Trees
- Leetcode Unique Binary Search Trees
- Leetcode: Unique Binary Search Trees
- [LeetCode] Unique Binary Search Trees
- Leetcode: Unique Binary Search Trees
- LeetCode | Unique Binary Search Trees
- Android Fragment学习笔记(一)----Fragment的生命周期和派生类
- SoapUI 调用外部java
- vs2010、vs2012下opencv2.4.9配置
- Android图片与屏幕适配问题
- fspecial,imfilter
- LeetCode Unique Binary Search Trees
- Android Fragment学习笔记(二)----Fragment界面添加和管理
- mybatis多个参数的传值
- 技术达人必备
- 二叉树(7)----求二叉树叶子节点个数,递归和非递归
- 一些第三方库
- 看书《DIV+CSS商业案例与网页布局开发精讲》_制作超链接_随手笔记
- Class.forName() 和 ClassLoader.loadClass()的区别
- Android Fragement学习笔记(三)----PreferenceFragment的使用