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
Note:
Binary Search Tree的特点:左边的分支只能存比root小的数,右边的分支只能存比root大的数。
所以每选定一个根节点,相当于将其余的n-1个数分成了两组,一组比根节点小,一组比根节点大。所以可以用递归解题。
Solution in Java 1:递归实现
public class Solution {
public int numTrees(int n) {
int sol =0;
if(n==0) return 1;
if(n==1) return 1;
for(int i=0; i<n; i++){
sol = sol+numTrees(i)* numTrees(n-i-1);
}
return sol;
}
}
注意左边分支和右边分支的解法应相乘得到一个选定root的解法总和。因为一个分支没有节点和只有一个节点都是一种解法,所以有初始条件: if(n==0) return 1;
if(n==1) return 1;
Solution in Java 2:Dynamic Programming
重复利用底层计算结果,节省一些时间。用数组solu[n+1]来储存中间计算结果。
故solu[i]表示含有i个结点的BST有多少个独特构造。故结果储存在solu[n]中。
public class Solution {
public int numTrees(int n) {
int[] solu = new int[n+1];
solu[0] = 1; //branch has 0 node, 1 unique BST
solu[1] = 1; //branch has 1 node, 1 unique BST
for(int i=2; i<n+1; i++){
for(int j=0; j<i; j++){ //j is the number of nodes in the left subtree,
//the max value of j is i-1 because there is 1 node to be root
solu[i] += solu[j]*solu[i-j-1]; //root has 1 node, left subtree has j nodes, so right subtree has i-j-1 nodes.
}
}
return solu[n];
}
}