[LeetCode] Unique Binary Search Trees(!!DP)

来源:互联网 发布:redial 软件 编辑:程序博客网 时间:2024/05/23 16:54

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

对于n,所以的可能解为根结点为1~n的解相加
对于根结点为i时,左儿子的可能性为根节点为i-1的子问题的解
右儿子的解为根结点为n-i的子问题的解。

class Solution {public:    int numTrees(int n) {        vector<int>  v(n+1,1);        vector<int> sum(n+1,0);        sum[0]=1;        getFac(n,v);        for(int i = 1; i<=n; ++i)            for(int j = 0; j<i; ++j)                sum[i] +=( sum[j]*sum[i-1-j]);        return sum[n];    }    void getFac(int n, vector<int> &v){        int f=1;        for(int i =1; i<=n; ++i){            f*=i;            v[i]=f;        }    }};

这里相当于提前求解了n!的阶乘 ,虽然总的算法复杂度是O(n),但实际上这个是冗余的计算。
假设G(n)是长度为n的BST的总的数目,那么

G(n) = G(0) * G(n-1) + G(1) * G(n-2) + … + G(n-1) * G(0)

而G[0]=G[1]=1;

于是

public int numTrees(int n) {    int [] G = new int[n+1];    G[0] = G[1] = 1;    for(int i=2; i<=n; ++i) {        for(int j=1; j<=i; ++j) {            G[i] += G[j-1] * G[i-j];        }    }    return G[n];}
0 0
原创粉丝点击