[Dynamic Programming] 96. Different binary search trees

96. Different binary search trees

Problem-solving ideas

  • base case dp[0] = 1 An empty node is also a binary tree
  • Status: dp[i] For each node i as the root node, how many binary search trees are there?
  • Outer loop: Traverse all possible node numbers. Memory loop traverses all left and right subtree combinations.
class Solution {
    
    
    public int numTrees(int n) {
    
    
        // base  case

        // dp[0] = 1  

        // 空节点 也是一颗二叉树


        int[] dp = new int[n + 1];

        dp[0] = 1;

        // 状态dp[i]  对于每一个节点i 作为根节点  那么它的二叉搜索树的数量有多少
        for(int i  = 1; i <= n; i++){
    
    
            for(int j = 1; j <= i; j++){
    
    
                // 左右子树 情况 相乘
                dp[i] += dp[i - j] * dp[j - 1];
            }
        }


        return dp[n];

    }
}

Guess you like

Origin blog.csdn.net/qq_44653420/article/details/133548681