Leetcode:unique_binary_search_trees
来源:互联网 发布:叁度软件破解版 编辑:程序博客网 时间:2024/06/07 14:07
一、 题目
给定数n,问有多少种不同的BST(二叉搜索树)
例如:
由于N =3,共有5种独特的BST。
1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3
二、分析
要求一定的二叉查找树的数量,我们知道二叉查找树可以任意取根。从处理子问题的角度来看,选取一个结点为根,可把结点分成左右子树,以这个结点为根的可行二叉树数量就是左右子树可行二叉树数量的乘积,所以总数量是将以所有结点为根的可行结果累加起来。
看到有人说到卡特兰数,这正是卡特兰数的一种定义方式,是一个典型的动态规划的定义方式。
卡特兰数的一半公式为Cn= 1/(n+1)*(2n,n) = (2n)!/{(n+1)!*n!}
class Solution {public: int numTrees(int n) { int flag=1; for(int i=2;i<=n;i++) { flag=2*(2*i-1)*flag/(i+1); } return flag; }};二: class Solution {public:int numTrees(int n) {return numTrees(1,n);}int numTrees(int start, int end){if (start >= end)return 1;int totalNum = 0;for (int i=start; i<=end; ++i)totalNum += numTrees(start,i-1)*numTrees(i+1,end);return totalNum;}};class Solution {public:int numTrees(int n) { if (n < 0) return 0; vector<int> trees(n+1, 0); trees[0] = 1; for(int i = 1; i <= n; i++) for (int j = 0; j < i; j++) trees[i] += trees[j] * trees[i-j-1]; return trees[n];}};
0 0
- Leetcode:unique_binary_search_trees
- leetcode--unique_binary_search_trees问题
- leetcode
- [leetcode]
- LeetCode
- leetcode
- leetcode
- leetcode:
- leetcode:
- LeetCode
- leetcode
- LEETCODE
- leetcode
- leetCode
- leetcode
- [leetcode]
- LeetCode
- leetcode
- 前缀表达式的求值
- Populating Next Right Pointers in Each Node II
- JQuery实现图片轮换
- Matlab程序转C++/OpenCV不可不知的17个函数
- 计算表达式的值c++逆波兰式实现方法
- Leetcode:unique_binary_search_trees
- Codeforces Bayan Bus
- iOS笔记--多点触碰的时候如何获取其中的某一次点击事件
- linux下fflush(stdin)的使用问题
- PHP搭建(windows64+apache2.4.7+mysql-5.6+php5.5+phpMyAdmin)和Discuz安装
- Maven配置笔记
- 归并排序
- bzoj1106: [POI2007]立方体大作战tet
- Ubuntu12.04安装libpcap-1.6.2