Leetcode96. 不同的二叉搜索树

96. 不同的二叉搜索树

Difficulty: 中等

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

示例:

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

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

Solution

思路:假设有n个结点,依次以每个结点为根结点,那么每次可以确定一个结点的位置,只要确定剩下n-1个结点位置,那么可以表示为(tree(i)=left*right),即以结点i为根结点的二叉搜索树个数为左子树的组合方式乘上右子树的组合方式。可以发现,n个点可以由n-1个点进行确定。公式表示有(f(i)=g(i-1)*g(m-i),i=1,2,...,m;m=1,2,...,n)其中,f(i)表示以编号为i为根结点的二叉搜索树个数,g(j)表示有j个结点的的树的个数。因为结点总数为m,所以第i个结点的左边有i-1个结点,第i个结点右边有m-i个结点。

Language: java

​class Solution {
    public int numTrees(int n) {
        int[] dp = new int[n+1];
        dp[0] = 1;
        for(int i=1; i<=n; i++){
            for(int j=1; j<=i; j++){
                dp[i] += dp[j-1] * dp[i-j];
            }
        }
        return dp[n];
    }
}
原文地址:https://www.cnblogs.com/liuyongyu/p/14444810.html