没思路,看了http://fisherlei.blogspot.com/2013/03/leetcode-unique-binary-search-trees.html 才恍然大悟。要多多练习找递推公式啊
这题想了好久才想清楚。其实如果把上例的顺序改一下,就可以看出规律了。
1 1 2 3 3
\ \ / \ / /
3 2 1 3 2 1
/ \ / \
2 3 1 2
比如,以1为根的树有几个,完全取决于有二个元素的子树有几种。同理,2为根的子树取决于一个元素的子树有几个。以3为根的情况,则与1相同。
定义Count[i] 为以[1,i]能产生的Unique Binary Tree的数目,
如果数组为空,毫无疑问,只有一种BST,即空树,
Count[0] =1
如果数组仅有一个元素{1},只有一种BST,单个节点
Count[1] = 1 [1]
如果数组有两个元素{1,2}, 那么有如下两种可能
1 2
\ /
2 1
Count[2] = Count[0] * Count[1] (1为根的情况) --> [1,2] 左边为空 count[0],右边只有一个元素count[1]
+ Count[1] * Count[0] (2为根的情况。 -->[1,2] 左边只有一个元素count[1],右边为空count[0]
再看一遍三个元素的数组,可以发现BST的取值方式如下:
Count[3] = Count[0]*Count[2] (1为根的情况) [1,2,3]
+ Count[1]*Count[1] (2为根的情况)[1,2,3]
+ Count[2]*Count[0] (3为根的情况)[1,2,3]
所以,由此观察,可以得出Count的递推公式为
Count[i] = ∑ Count[i] * [ n-1-i] 0<=i<=n-1
问题至此划归为一维动态规划。
package Level3;
/**
* Unique Binary Search Trees
*
* 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
*
*/
public class S96 {
public static void main(String[] args) {
System.out.println(numTrees(3));
}
// 递归公式cnt[i] = sum(cnt[0]*cnt[i-1], cnt[1]*cnt[i-2], cnt[2]*cnt[i-3], ..., cnt[i-1]*cnt[0])
public static int numTrees(int n) {
int[] cnt = new int[n+1];
cnt[0] = 1;
cnt[1] = 1;
for(int i=2; i<=n; i++){
for(int j=0; j<=i-1; j++){
cnt[i] += cnt[j] * cnt[i-1-j];
}
}
return cnt[n];
}
}
补上递归解法:
算法:1~n中每个数字都可以是root,定了谁是root之后(比如k),他的左子树只能是1~k-1组成的,右子树只能是k+1~n组成的。左子树的variation数目×右子树的就是k作为root的有几种rotation。有点要注意:终止条件有两种:
- p == q,说明就一个节点了,没啥可转的,就一种return 1
- p > q,说明这一段已经不存在了,这时不应该return 0,因为这正是子树是null的情况!所以还应该return 1
public class Solution {
public int numTrees(int n) {
return numTreesR(1, n);
}
public int numTreesR(int begin, int end){
if(begin >= end){
return 1;
}
int cnt = 0;
for(int i=begin; i<=end; i++){
int leftNum = numTreesR(begin, i-1);
int rightNum = numTreesR(i+1, end);
cnt += leftNum * rightNum;
}
return cnt;
}
}