leetcode--Unique Binary Search Trees
来源:互联网 发布:apache 压力测试工具 编辑:程序博客网 时间:2024/06/06 09:51
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
思路:有点类似斐波那契数列。
class Solution {public: int numTrees(int n) { if(n<=0)return 0; int tmp[n+1]={0}; tmp[0] = 1; tmp[1] = 1; for(int i=2;i<=n;i++) { for(int j=0;j<i;j++) { tmp[i] += tmp[j]*tmp[i-j-1]; } } return tmp[n]; }};或者class Solution {private: vector<TreeNode*> helper(int start, int end){ vector<TreeNode*> res; if(start > end) { res.push_back(NULL); return res; } for(int i = start; i <= end; i++){ vector<TreeNode*> lefts = helper(start, i - 1); vector<TreeNode*> rights = helper(i + 1, end); for(int j = 0; j < (int)lefts.size(); j++){ for(int k = 0; k < (int)rights.size(); k++){ TreeNode* root = new TreeNode(i); root->left = lefts[j]; root->right = rights[k]; res.push_back(root); } } } return res; }public: vector<TreeNode*> generateTrees(int n) { if(n == 0) return vector<TreeNode*>(0); return helper(1,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
- Go语言defer
- hdu 3449 consumer 有依赖的背包问题
- Centos7中anaconda的安装配置之忘记添加环境变量怎么办-->XGboost安装-->vi退出
- 126邮箱登陆 打印title
- Python:eval的妙用和滥用
- leetcode--Unique Binary Search Trees
- 注:Python中Scrapy爬虫框架的安装和pywin32安装的问题(py 3.x版本)
- 189. Rotate Array 旋转数组
- 使用scala实现Akka底层的rpc通信
- javascript中this 的指向问题(二)
- leetcode--Triangle
- commons-fileupload实现文件上传
- 523. Continuous Subarray Sum
- wprintf或_tprintf不显示问题