LeetCode 20200129 (different binary search tree)

1. The binary search tree different
from the angle-by recursive calculation
similar to the calculation deed Fibonacci number sequence
consider one kind of nodes 0 (empty tree)
a node one kind of
two nodes, it is the consider the first fixed node as a root and then divided into two ah one is left subtree right subtree of nodes 0 to 1 and the other is left to right is 1 0 3,4 node, where n continues to accumulate

class Solution {
        int numTrees(int n) {
        //dp[i]表示有i个结点时二叉树有多少种可能
        int[] dp = new int[n + 1];
        //初始化
        dp[0] = 1;
        dp[1] = 1;
        
        //因为计算dp[n]需要知道dp[0]--->dp[n-1]。所以第一层循环是为了求dp[i]
        for (int i = 2; i <= n; i++) {
            //当有i个结点时,左子树的节点个数可以为0-->i-1个。剩下的是右子树。
            for (int j = 0; j < i; j++) {
                dp[i] += dp[j] * dp[i - j - 1];
            }
        }
        return dp[n];
    }
};
Published 44 original articles · won praise 9 · views 3339

Guess you like

Origin blog.csdn.net/puying1/article/details/104106445