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