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

描述

给定一个整数 n,求以 1 ... n 为节点组成的二叉搜索树有多少种?

示例:

输入: 3
输出: 5
解释:
给定 n = 3, 一共有 5 种不同结构的二叉搜索树:

   1         3     3      2      1
    \       /     /      / \      \
     3     2     1      1   3      2
    /     /       \                 \
   2     1         2                 3

解法

class Solution {
    public int numTrees(int n) {
        int[] G = new int[n+1];
        G[0] = 1; 
        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];
    }
}

时间复杂度: o(N2), 空间复杂度: o(N) 

G(N) = f(1) + ...  + f(n)

f(n) = G(i-1)*G(n-i) + ... + G(n-1)*G(n-n)

这个是该算法的精髓

参考:https://leetcode-cn.com/problems/unique-binary-search-trees/submissions/

 

猜你喜欢

转载自www.cnblogs.com/wangsong412/p/12516208.html