[LeetCode]Unique Binary Search Trees

来源:互联网 发布:sas 优化案例 编辑:程序博客网 时间:2024/06/13 23:29

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,i1)f(i+1,n)

实际上,

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

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

f(n)=i=1nf(i1)f(ni)

然后我们利用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[n];    }}
0 0
原创粉丝点击