Java implementation of LeetCode 96 different binary search tree

96. Different binary search tree

Given an integer n, 1 ... n is seeking to nodes of a binary search tree, how many?

Example:

Input: 3
Output: 5
Explanation:
Given n = 3, a total of 5 different binary search tree structure:

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

PS:
Dynamic Programming

The number of binary sort tree presence of n nodes is assumed that G (n), so that f (i) is the number i to the root of the binary search tree

即有:G(n) = f(1) + f(2) + f(3) + f(4) + … + f(n)

n is a root node, when i is a root node, and the number of left sub-tree nodes [1,2,3, ..., i-1], the number of the right subtree for the node [i + 1, i + 2, ... n-], i is a root node when the number of left sub-tree node which is i-1 th, right subtree of node Ni, i.e., f (i) = G (i-1) * G (ni),

The above two formulas can be obtained: G (n-) = G (0) G (n--. 1) G + (. 1) (n--2) + ... + G (n--. 1) G * (0)

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];
    }
}
Released 1214 original articles · won praise 10000 + · Views 650,000 +

Guess you like

Origin blog.csdn.net/a1439775520/article/details/104374028