LeetCode
来源:互联网 发布:阿里云大厦今日头条 编辑:程序博客网 时间:2024/06/05 04:53
96. Unique Binary Search Trees
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这些数可以构成多少棵二叉树。
给定一个序列1~n,为了构造所有二叉树,我们可以使用1~n中的每一个数i作为根节点,自然1~(i-1)必然位于树的左子树中,(i+1)~n位于树的右子树中。然后可以递归来构建左右子树,由于根节点是唯一的,所以可以保证构建的二叉树都是唯一的。
使用两个状态来记录:
G(n):长度为n的序列的所有唯一的二叉树。
F(i, n),1<=i<=n:以i作为根节点的二叉树的数量。
G(n)就是我们要求解的答案,G(n)可以由F(i,n)计算而来。
G(n)=F(1,n)+F(2,n)+...+F(n,n) (1)
G(0)=1,G(1)=1
对于给定的一个序列1.....n,我们取i作为它的根节点,那么以i作为根节点的二叉树的数量F(i)可以由下面的公式计算而来:
F(i,n)=G(i-1)*G(n-i) 1<=i<=n (2)
综合公式(1)和公式(2),可以看出:
G(n) = G(0) * G(n-1) + G(1) * G(n-2) + … + G(n-1) * G(0)
这就是上面这个问题的答案。
时间复杂度O(n^2),空间复杂度O(n)
class Solution {public: int numTrees(int n) { vector<int> ans(n+1, 0); ans[0] = 1; ans[1] = 1; for (int i = 2; i <= n; ++i) { for (int j = 0; j < i; ++j) { ans[i] += ans[j] * ans[i-j-1]; } } return ans[n]; }};
95. Unique Binary Search Trees II
Given an integer 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将上题构造的二叉树都输出。
当前的递归中,假设root为i。那么显然左子树是由[1,i-1]构成的所有可能的组合,显然右子树是由[i+1,n]构成的所有可能的组合(可以统一记录为,用[start, end]去构建树)。在有了左子树,root,右子树的情况下,根据乘法原理很容易计算得出在当前情况下的所有的树。记录root到一个vector中就可以完整地记录所有结果。返回结果即可。
/** * 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) return vector<TreeNode*> {}; return solve(1, n); } vector<TreeNode*> solve(int st, int ed) { if (st > ed) return vector<TreeNode*> {NULL}; vector<TreeNode*> ans; for (int i = st; i <= ed; ++i) { vector<TreeNode*> le = solve(st, i - 1); vector<TreeNode*> ri = solve(i + 1, ed); for (int j = 0; j < le.size(); ++j) { for (int k = 0; k < ri.size(); ++k) { TreeNode* cur = new TreeNode(i); cur->left = le[j]; cur->right = ri[k]; ans.push_back(cur); } } } return ans; }};
- leetcode
- [leetcode]
- LeetCode
- leetcode
- leetcode
- leetcode:
- leetcode:
- LeetCode
- leetcode
- LEETCODE
- leetcode
- leetCode
- leetcode
- [leetcode]
- LeetCode
- leetcode
- leetcode:
- leetcode
- ES6新特性浅析
- 查看mongodb当前配置的命令
- c# 实现Picturebox的鼠标拖拽功能
- 获取手机wifi或4g网络的IP地址
- 分布式消息队列之大型网站架构
- LeetCode
- android通过代码获得sha1的值
- Json:前台对象数组传到后台解析
- unity3D中如何分别获取pc端鼠标的滑动方向和andriod移动平台上手指的滑动方向?
- ajax请求+vue.js渲染+页面加载
- 欧拉线性筛法求素数(顺便实现欧拉函数的求值)
- python爬虫利器-bs
- 国产免费虚拟化OVM与 OpenStack对比
- HDU1009 FatMouse' Trade 贪心