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

[LeetCode]Unique Binary Search Trees

2016-11-15 19:28 441 查看
Question

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


本题难度Medium。

DP

【复杂度】

时间 O(N) 空间 O(N)

【思路】

可以参照(复习)[LeetCode]Unique Binary Search Trees II,设n的BST的个数为
f(1,n)
,则可以看到:

f(1,n)=∑i=1nf(1,i−1)∗f(i+1,n)

实际上,

f(i+1,n)=f(1,n−i)

因此可以进一步地化简,我们用
f(n)
表示BST的个数,则:

f(n)=∑i=1nf(i−1)∗f(n−i)

然后我们利用DP对
f(0)
f(n)
的值依次进行计算即可。

【代码】

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