[Dynamic Programming] LeetCode-96. Different Binary Search Trees

96. Different Binary Search Trees

Title description

Given an integer n, how many kinds of binary search trees are there with 1… n as nodes?

Example:

Input: 3
Output: 5
Explanation:
Given n = 3, there are 5 binary search trees with different structures:

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

Problem-solving ideas

class Solution_96 {
    
    
    public int numTrees(int n) {
    
    
        int[] dp = new int[n + 1];
        dp[0] = 1;
        dp[1] = 1;
        for (int i = 2; i < n + 1; i++) {
    
    
            for (int j = 1; j < i + 1; j++) {
    
    
                dp[i] += dp[j - 1] * dp[i - j];
            }
        }
        return dp[n];
    }
}

Guess you like

Origin blog.csdn.net/qq_35655602/article/details/115017106