题目:https://oj.leetcode.com/problems/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分析:
当数组为1,2, 3... n 时,基于以下原则的构建的BST 树具有唯一性:以i 为根节点的树,其左子树由[1, i-1] 构成,其右子树由[i+1, n] 构成。
定义f(i) 为以[1; i] 能产生的Unique Binary Search Tree 的数目,则
如果数组为空,毫无疑问,只有一种BST,即空树,f(0) = 1。
如果数组仅有一个元素1,只有一种BST,单个节点,f(1) = 1。
f(2) = f(0) f(1) ,1 为根的情况
+ f(1) f(0) ,2 为根的情况
再看一看3 个元素的数组,可以发现BST 的取值方式如下:
f(3) = f(0) f(2) ,1 为根的情况
+ f(1) f(1) ,2 为根的情况
+ f(2) f(0) ,3 为根的情况
所以,由此观察,可以得出f 的递推公式为
至此,问题划归为一维动态规划。
源码:Java版本
算法分析:时间复杂度O(n^2),空间复杂度O(n)。
public class Solution {
public int numTrees(int n) {
int[] f=new int[n+1];
f[0]=1;
f[1]=1;
for(int i=2;i<=n;i++) {
for(int j=0;j<=i-1;j++) {
f[i]+=f[j]*f[i-1-j];
}
}
return f[n];
}
}