96 different binary search tree

Title Description

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

Ideas analysis

First observation, we can see the sequence 1-n, selected from the roots do i, 1-i of the left subtree is the right subtree in, i is the number of different roots is about bst product subtrees different situations.

eg. 1234, selected from the roots do 2, a left subtree, right subtree 34, corresponding to F (2,4) = O (1) * O (2)

This discovery will expand to the whole, can be found in O (n-) = [Sigma
O (-I. 1) * O (Ni).

Recursive solution complexity is high, with a move regulation. Regulation can move large problem into smaller problems and solutions of sub-problems that can store both!

Note: Look resolved only to find that this is the number Cartland.

Code

    public int numTrees(int n) {
        int[] dp = new int[n + 1];
        dp[0] = 1;
        dp[1] = 1;

        for (int i = 2; i <= n; i++) {
            for (int j = 1; j <= i; j++) {
                dp[i] += dp[j - 1] * dp[i - j];
            }
        }
        return dp[n];
    }
Published 117 original articles · won praise 8 · views 3700

Guess you like

Origin blog.csdn.net/qq_34761012/article/details/104566393