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. 递归解法
思路1:
首先明白什么是二分搜索树,左子树的关键字都小于父结点的关键字,右子树的关键字都大于父结点的关键字。具体思路,参考[1]的思路,很容易理解。
当给定 n 时,要求出有 n 个节点的不重复的二叉查找树。即就是求出以 i 为根节点的所有不重复二叉查找树的和,其中 i 从 1 到 n。而当 i 为根节点时,1~i-1 都在根节点的左子树上,i+1~n 都在根节点的右子树上。而左右子树也都是二叉查找树。根据排列组合可以知道,当i为根节点时,不重复二叉查找树的数量因该是左子树的数量乘以右子树的数量。即Root( i ) = numTrees( i - 1 ) * numTrees( n - i )。
所以 numTrees( n ) = Root( 1 ) + Root( 2 ) + Root( 3 ) + …… + Root( n ).
class Solution {
public:
int numTrees(int n) {
int num, i;
num = 0;
if (n == 0 || n == 1)
return 1;
for (i = 1; i <= n; i ++)
num += numTrees(i - 1) + numTrees(n - i);
return num;
}
};
leetcode报TLE。
动态规划
思路2:
参考2中的思路,其实和思路1类似,只是思路1中递归有多次重复计算,思路2是将前面计算过的结果保存起来,不需要再重复计算,用空间换取时间,时间复杂度是O(N^2)。
class Solution {
public:
int numTrees(int n) {
if (n == 0 || n == 1)
return 1;
vector<int> res(n + 1);
int i, j, lnum, rnum;
res[0] = 1;
res[1] = 1;
for (i = 2; i <= n; i ++) {
res[i] = 0;
for (j = 0; j < i; j ++) {
lnum = res[j];
rnum = res[i - j - 1];
res[i] += lnum * rnum;
}
}
return res[n];
}
};
参考:
[1] http://blog.youkuaiyun.com/wj529975782/article/details/37730163
[2] http://blog.unieagle.net/2012/11/01/leetcode题目:unique-binary-search-trees,一维动态规划/