leetcode No.96 不同的二叉搜索树

class Solution {
    public int numTrees(int n) {
        //参考热评第一  时间复杂度beat100%
        // 结题思路:假设n个节点存在二叉排序树的个数是G(n),1为根节点,2为根节点,
        // ...,n为根节点,当1为根节点时,其左子树节点个数为0,右子树节点个数为n-1,
        // 同理当2为根节点时,其左子树节点个数为1,右子树节点为n-2,所以可得
        // G(n) = G(0)*G(n-1)+G(1)*(n-2)+...+G(n-1)*G(0)
        int[] f=new int[n+1];
        if(n==0) return 1;
        f[0]=1;
        for(int i=1;i<=n;++i){
            f[i]=0;
            for(int j=0;j<i;++j){
                f[i]+=f[j]*f[i-j-1];
            }
        }
        return f[n];
    }
}

猜你喜欢

转载自blog.csdn.net/qq_33399567/article/details/88998169