一.题目
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
Show Tags
Have you met this question in a real interview?
Yes
No
二.解题技巧
对于二叉查找树来说,对于一个结点而言,其左子树的上所有结点的值都是小于该结点的,其右子树上所有结点的值都是大于该结点的。因此,由于输入的数组的值为1,2,3,...,n,因此,对于数值k而言,其左子树的结点的个数为k-1个,右子树的结点的个数为n-k个,因此当数值为k的结点作为父结点时,二叉查找树的个数a(k)=a(k-1)*a(n-k)。因此,可以通过递归调用来计算a(k)的值。因此,含有n个数的数组所能形成的二叉查找树的个数为s(n)=a(1)+a(2)+a(3)+...+a(n)。
从上面的计算方式可以看出,对于每一个a(k)都会被用到多次,因此,可以考虑将这些值用一个表保存下来,这样,下一次使用的时候就是一个查表的过程,而不是计算的过程,这样就可以用空间来换的计算时间上面的提升。这个也就是使用动态规划思想来解决这个问题。
上面的方法的空间复杂度为O(n),时间复杂度为O(n^2)。
三.实现代码
#include <unordered_map>
using std::unordered_map;
class Solution
{
private:
unordered_map<int, int> PreResult;
public:
int numTrees(int n)
{
if (n == 0)
{
PreResult[0] = 1;
return 1;
}
if (n == 1)
{
PreResult[1] = 1;
return 1;
}
if (PreResult.find(n) != PreResult.end())
{
return PreResult[n];
}
int Result = 0;
for (int HeadIndex = 1; HeadIndex <= n; HeadIndex++)
{
int LeftChildResult = numTrees(HeadIndex - 1);
int RightChildResult = numTrees(n - HeadIndex);
Result += LeftChildResult * RightChildResult;
}
PreResult[n] = Result;
return Result;
}
};
四.体会
这道题在考虑二叉查找树的性质的同时,也考虑到使用动态规划来利用空间换时间,这是一道比较有趣的题,同时考察了两个方面的知识。
版权所有,欢迎转载,转载请注明出处,谢谢
![微笑](http://static.blog.csdn.net/xheditor/xheditor_emot/default/smile.gif)