Unique Binary Search Trees - Leetcode
来源:互联网 发布:当红网络歌曲 编辑:程序博客网 时间:2024/06/05 07:22
public class Solution { public int numTrees(int n) { if(n==0 || n==1) return 1; int[] f = new int[n+1]; for(int i=0; i<n+1; i++){ if(i<2) f[i]=1; else{ int val=0; for(int j=0; j<i;j++){ val += f[j]*f[i-1-j]; } f[i]=val; } } return f[n]; }}
写法2:
public class Solution { public int numTrees(int n) { if(n==0 || n==1) return 1; int[] f = new int[n+1]; int val; f[0]=1; f[1]=1; for(int i=2; i<n+1; i++){ val = 0; for(int k=0; k<i; k++) val += f[k]*f[i-1-k]; f[i] = val; } return f[n]; }}
分析:找规律 -
没有节点的时候是f(0)=1,
一个节点的时候 f(1)=1,
2个节点的时候【0+1; 1+0】f(2)=f(0)*f(1)+f(1)*f(0)
3个节点的时候f(3)= f(0)*f(2)+f(1)*f(1)+f(2)*f(0)
N个节点f(n)=f(0)*f(n-1)+ f(1)*f(n-2) +..... f(n-1)*f(0)
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
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
- IO包中的其他流对象
- 关于MyEclipse 10 部署报错或者无法部署问题的解决方案
- Universal Windows App Development with Cortana and the Speech SDK 3
- java jxl处理excel
- python中那些双下划线开头得函数和变量
- Unique Binary Search Trees - Leetcode
- FFMPEG使用参数详解
- linux设备驱动异步通知
- MyEclipse 启动报错:'Building workspace' has encountered a problem解决方法
- iOS客户端学习-Prefix.pch文件
- 面试题 以下程序的输出结果是什么
- Getting Started with ASP.NET MVC 5
- 【转载】Android的三种网络通信方式
- linux动态链接库全局变量共享问题&DLL共享数据段