LeetCode-96. Unique Binary Search Trees
2016-02-21 11:55
337 查看
Description:
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.
问题大意:给一个整数n,计算出节点数为n的二叉查找树的种类。
这个题目最简单的思路应该是递归构造二叉查找树,让每个节点都成为根节点。这样时间复杂度较高。还有一种动态规划法。描述如下:
假如整个树有 n 个节点,根节点为 1 个节点,两个子树平分剩下的 n-1 个节点。
假设我们已经知道节点数量为 x 的二叉树有
则一颗二叉树左节点节点数量为 k 时,其形态数为
而对于一颗 n 个节点的二叉树,其两个子树分配节点的方案有 n-1 种:
因此我们可以得到对于 n 个节点的二叉树,其形态有:
并且可以发现,
边界条件为
以上分析来源这里
Java代码:
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,计算出节点数为n的二叉查找树的种类。
这个题目最简单的思路应该是递归构造二叉查找树,让每个节点都成为根节点。这样时间复杂度较高。还有一种动态规划法。描述如下:
假如整个树有 n 个节点,根节点为 1 个节点,两个子树平分剩下的 n-1 个节点。
假设我们已经知道节点数量为 x 的二叉树有
dp[x]种不同的形态。
则一颗二叉树左节点节点数量为 k 时,其形态数为
dp[k] * dp[n - 1 - k]。
而对于一颗 n 个节点的二叉树,其两个子树分配节点的方案有 n-1 种:
(0, n-1), (1, n-2), ..., (n-1, 0)
因此我们可以得到对于 n 个节点的二叉树,其形态有:
Sigma(dp[i] * dp[n-1-i]) | i = 0 .. n-1
并且可以发现,
dp数组有递推关系,我们可以使用递推或是记忆化搜索来实现。
边界条件为
dp[0] = 1。
以上分析来源这里
Java代码:
public class Solution { int[] rc; public int numTrees(int n) { rc = new int[n+1]; Arrays.fill(rc, 0); return dp(n); } public int dp(int nodes) { if(nodes <= 1) return 1; if(rc[nodes] != 0) return rc[nodes]; int numTrees = 0; for(int i=0; i<nodes; i++) { numTrees += dp(i) * dp(nodes-i-1); } rc[nodes] = numTrees; return numTrees; } }
相关文章推荐
- Root exploit for Android (adb setuid)
- ANDROID_MARS学习笔记_S04_001_OAUTH获取request_token
- iOS组件之UIScrollView
- EasyUI闪屏,EasyUI页面加载提示:原理+代码+效果图
- EasyUI闪屏,EasyUI页面加载提示:原理+代码+效果图
- EasyUI闪屏,EasyUI页面加载提示:原理+代码+效果图
- androidUI-对话框
- 报错No resource found that matches the given name (at 'title' with value '@string/action_settings'
- 在easyui datagrid中formatter数据后使用linkbutton
- UI整理-----part5--UICollectionView
- 用UIInterpolatingMotionEffect产生透视效果
- ios-基础用法之【3】-import和inclue的区别
- android进行异步更新UI的四种方式(转载)
- UI_拖动View
- LeetCode Closest Binary Search Tree Value II
- 【POJ】[1679]The Unique MST
- LeetCode Closest Binary Search Tree Value
- UICollectionView自定义Layout之蜂窝布局
- reveal UI 分析工具简单使用 内附1.5.1破解版下载地址
- We Recommend a Singular Value Decomposition