您的位置:首页 > 产品设计 > UI/UE

[LeetCode] Unique Binary Search Trees

2014-05-22 15:41 337 查看
题目:

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

解答:
class Solution {
public:
int numTrees(int n) {
vector<int> num;
num.push_back(1);
num.push_back(1);
if(n == 0) {
return num[0];
}
else if(n == 1) {
return num[1];
}
else {
for(int j = 2; j <= n; j ++) {
int sum = 0;
for(int i = 0; i < j; i++) {
sum = sum + num[i] * num[j - i - 1];
}
num.push_back(sum);
}
}
return num
;
}
};


思路:

n的结果与n-1的结果是相关联的,首先直观给出计算公式:以n=3为例,f(3)=0*2+1*1+2*0,看出来规律了吗?

我们可以这么想,n从2变成3,即多了一个点,可以把这个点当做根节点,那么根节点引出左右两个孩子,左孩子可以是2/1/0个节点,相应右孩子则为0/1/2个节点,那么总情况数就是左孩子节点个数的情况数×右孩子节点个数的情况数加和。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: