96. Unique Binary Search Trees(I 和 II)
2016-03-09 15:50
519 查看
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.
https://leetcode.com/discuss/24282/dp-solution-in-6-lines-with-explanation-f-i-n-g-i-1-g-n-i
如果F(n)表示长度为n的二叉树有多少种结果,则
所以代码如下:
For example,
Given n = 3, your program should return all 5 unique BST’s shown below.
同样沿用 I 的思路,利用分治思想
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
https://leetcode.com/discuss/24282/dp-solution-in-6-lines-with-explanation-f-i-n-g-i-1-g-n-i
如果F(n)表示长度为n的二叉树有多少种结果,则
F(n) = F(0)*F(n-1) + F(1)*F(n-2) + F(2)*F(n-2) + ......+ F(n-1)*F(0)
所以代码如下:
class Solution { public: int numTrees(int n) { if(n <= 0) return 0; vector<int> nums(n+1,0); nums[0] = 1; for(int i = 1; i<=n; i++){ for(int j = 1; j <=i ; j++){ nums[i] += nums[j-1]*nums[i-j]; } } return nums ; } };
Unique Binary Search Trees II
Given n, generate all structurally unique BST’s (binary search trees) that store values 1…n.For example,
Given n = 3, your program should return all 5 unique BST’s shown below.
1 3 3 2 1 \ / / / \ \ 3 2 1 1 3 2 / / \ \ 2 1 2 3
同样沿用 I 的思路,利用分治思想
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<TreeNode*> generateTrees(int n) { if(n <=0) return vector<TreeNode*>(); return generateSubTrees(1,n); } vector<TreeNode*>generateSubTrees(int s,int e){ vector<TreeNode*> res; if(s > e){ res.push_back(NULL); return res; } for(int i = s; i <= e;i++ ){ vector<TreeNode*> left = generateSubTrees(s,i-1); vector<TreeNode*> right = generateSubTrees(i+1,e); for(auto l : left){ for(auto r : right){ TreeNode* root = new TreeNode(i); root->left = l; root->right = r; res.push_back(root); } } } return res; } };
相关文章推荐
- iOS 利用UISCrollView作广告自动轮播效果
- 太原UI设计师郭文军讲网页设计及web前端网页宽度要求?
- 【LeetCOde】62. Unique Paths
- QueryRunner 之 query函数
- 错误"Invalid value around character 0"
- 双向map,通过value找到key,还有...
- question about import google file
- UIBezierPath精讲
- UIAlertController
- BuiltWith
- 【bzoj1670】[Usaco2006 Oct]Building the Moat护城河的挖掘 凸包
- Android Volley完全解析(三),定制自己的Request
- HTML--11marquee标签
- com.mysql.jdbc.PacketTooBigException: Packet for query is too large (4200044 > 1048576). You can cha
- Django中远程服务器访问bad request
- 《iOS Human Interface Guidelines》——Scope Bar
- UICollectionView中layoutsubView的坑
- 1062. Talent and Virtue (25) 排序
- 《iOS Human Interface Guidelines》——Search Bar
- PHP中的break与continue