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

96. Unique Binary Search Trees

2017-01-07 23:45 323 查看
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.



思路:动态规划。当n=7的时候,1为根结点,左边0个节点,右边6个节点和7为根结点对称,这种情况的个数为2*F[0]*F[6]。2为根结点,左边1个节点,右边5个节点,和6为根节点对称,个数为2*F[1]*F[5]

3为根结点,左边2个节点,右边4个节点,和5为根结点对称,个数为2*F[2]F[4]。当4为根节点,左边3个,右边3个,个数为F[3][3]。

当n为偶数,同理。

class Solution {
public:
int numTrees(int n) {
double *F = new double[n + 1];
memset(F, 0, sizeof(F));
F[0] = 1;
F[1] = 1;
for(int i = 2; i <= n; ++i){
for(int j = 1; j <= (i / 2); ++j)
F[i] += F[i - j] * F[j - 1] * 2;
if(i % 2 != 0){
F[i] += F[i / 2] * F[i / 2];
}
}
return F
;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: