LintCode:M-不同的二叉查找树个数
来源:互联网 发布:广电网络能吃鸡吗 编辑:程序博客网 时间:2024/06/08 15:39
LintCode链接
给出 n,问由 1...n 为节点组成的不同的二叉查找树有多少种?
样例
给出n = 3,有5种不同形态的二叉查找树:
1 3 3 2 1 \ / / / \ \ 3 2 1 1 3 2 / / \ \2 1 2 3
标签
public class Solution { /** * @paramn n: An integer * @return: An integer */ public int numTrees(int n) { int[] dp = new int[n+1]; dp[0]=1; return helper(dp, n); } //方法一 //记忆+递归 public int helper(int[] dp, int n) { if(dp[n]>0) return dp[n]; //每个node做root情况下的种数 for(int i=1; i<=n; i++){ dp[i-1] = dp[i-1]>0?dp[i-1]:helper(dp, i-1); dp[n-i]= dp[n-i]>0?dp[n-i]:helper(dp, n-i); dp[n] += dp[i-1]*dp[n-i]; } return dp[n]; } //方法二 //AC=95% //超时 public int helper_1(int n) { if(n==0) return 1; int res=0; //每个node做root情况下的种数 for(int i=1; i<=n; i++){ int left=helper_1(i-1); int right=helper_1(n-i); res += left*right; } return res; } }
阅读全文
0 0
- LintCode:M-不同的二叉查找树个数
- LintCode-不同的二叉查找树 II
- LintCode-不同的二叉查找树
- lintcode-不同的二叉查找树-163
- LintCode 不同的二叉查找树
- LintCode:不同的二叉查找树
- 不同的二叉查找树 II lintcode
- lintcode,不同的二叉查找树
- LintCode 163-不同的二叉查找树
- LintCode :不同的二叉查找树
- lintcode-不同的二叉查找树
- 不同的二叉查找树-LintCode
- 不同的二叉查找树 II -LintCode
- lintcode --不同的二叉查找树
- lintcode--不同的二叉查找树II
- lintcode:不同的二叉查找树
- LINTCODE——不同的二叉查找树
- LintCode:M-二叉查找树中搜索区间
- 浅析ReentLock的使用
- php杂项函数总汇(很实用的未归类函数)
- 2018大疆校招软件岗位笔试题目(求有效工作时间)——未在线验证
- 串口操作经验总结
- contiki之uip-ds6-route头文件
- LintCode:M-不同的二叉查找树个数
- 单例模式:双重锁校验可能存在的问题。
- Java 多线程join方法
- 编译选项默认关闭adb RSA指纹认证
- Csharp进阶:文件流之Directory类和DirectoryInfo类,FileStream 类
- 求逆序对
- 19_字符串移位包含问题
- tableViewCell设置底部线长度与屏幕等宽(备忘)
- hdu2966 In case of failure(这道题就和ta的name一样,failure)