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

LeetCode题解:Unique Binary Search Trees

2014-11-06 16:39 330 查看

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

思路:

典型的动态规划题目。

BST(n) = Sum(i, 1, n, BST(i - 1) * BST(n - i))


其中(i, 1, n)表示i的取值范围从1到n。

题解:

class Solution {
public:
vector<int> history;

Solution()
{
history.push_back(1);
history.push_back(1);
history.push_back(2);
}

int numTrees(int n)
{
while(history.size() <= n)
{
int last = history.size();
int accumu = 0;
for(int i = 1 ;i <= last; ++i)
accumu += history[i - 1] * history[last - i];
history.push_back(accumu);
}

return history
;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  算法