leetcode96. Different binary search tree move return vs mathematics?

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

Ideas: dp [n] represents the answer, dp [n] =

A left subtree node, right child node n-1

Left subtree node 2, n-2 right subtree node

................................

Left subtree of n-1 nodes, a right child node

All cases add up.

public class Solution {
  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];
  }
}

There is a mathematical official, too strong.

Published 465 original articles · won praise 8593 · Views 1.08 million +

Guess you like

Origin blog.csdn.net/hebtu666/article/details/104085228