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

[LeetCode OJ]Unique Binary Search Trees

2014-11-05 20:57 267 查看
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

设U(1, 2, ..., n)代表存储1...n的binary search tree的数目。dp(i, n-1)代表以i为根,包含n-1个子结点的二叉树数目。
U(1, 2, ..., n) = dp(1, n-1) + dp(2, n-1) + ... dp(n, n-1).
Clearly, dp(i, n-1) = U(1, 2, ..., i-1) * U(i+1, i+2, ..., n),

and U(i+1, i+2, ..., n) = U(1, 2, ..., n-i).
Thus, dp(i, n-1) = U(1, 2, ..., i-1) * U(1, 2, ..., n-i).

不妨简记U(n) = U(1, 2, ..., n), 那么
U(n) = U(0)*U(n-1) + U(1)*U(n-2) + ... + U(i-1)*U(n-i) + ... + U(n-1)*U(0), 1 <= i <=n.

Example.
U(0) = 1
U(1) = 1
U(2) = dp(1, 1)+dp(2, 1) = U(0)*U(1) + U(1)*U(0) = 2
U(3) = dp(1, 2)+dp(2, 2)+dp(3, 2) = U(0)*U(2) + U(1)*U(1) + U(2)*U(0) = 2 + 1 + 2 = 5

class Solution {
public:
int numTrees(int n) {
vector<int> num(n+1, 0);

num[0] = 1;

for(int i = 1; i <= n; i++) {
for(int j = 0; j < i; j++)
num[i] += num[j] * num[i - j - 1];
}

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