LeetCode 96. Different Binary Search Trees

 

Topic description

 

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

 

Example:

Inputs: 3 
Outputs: 5
explain:
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

 

This problem is actually the application of constructing Cattelan numbers, which is solved by the idea of ​​dynamic programming. For n nodes, excluding the root node, there are still n-1 nodes left, so the number of nodes in the left and right subtrees is allocated as follows:

(0,n-1), (1,n-2), (2, n-3), ....(n-1,0)

We can simply get:

  • When n=0, the number of species is dp(n)=1;
  • When n=1, the number of species is dp(n)=1;

Then the types of binary trees with n nodes can be calculated in turn, namely:

dp(n)=dp(0)*dp(n-1)+dp(1)*dp(n-2)+dp(2)*dp(n-3)+...+dp(n-1)*dp(0)

In addition, the Cattelan number formula can also be directly constructed to solve:

dp(n)=C(2n,n)/(n+1)

 

code

 

 1 class Solution {
 2 public:
 3     int numTrees(int n) {
 4         vector<int> dp(n+1,0);
 5         dp[0]=1;
 6         dp[1]=1;
 7         for(int i=2;i<=n;i++)
 8             for(int j=0;j<i;j++)
 9                 dp[i]+=dp[j]*dp[i-j-1];
10         return dp[n];
11     }
12 };

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325299041&siteId=291194637