topic:
Given n, how many structurally unique BST's (binary search trees) that store values 1...n?
For example,
Given n = 3, there are a total of 5 unique BST's.
Analysis of the meaning of the title:
This problem is given an integer n, find the number of binary search trees from 1 to n.
We all know that the binary search tree is traversed in order to obtain a sequence from small to large, which is a sequence from 1 to n for this problem. Since I just learned dynamic programming recently, I tried to solve this problem with the idea of dynamic programming.
For all binary search trees from 1 to n, then every node may be the root node. If we select the i-th node as the root node, then its left subtree will be protected from 1 to i-1 after inorder traversal, then its right subtree will also be obtained from i+1 to n after inorder traversal such a sequence. We only need to find out how many binary search trees f(i-1) there are from 1 to i-1 and then find out how many binary search trees there are from i+1 to n-1. Then f(i)=f(i-1)*f(ni).
And f(n) is the sum of the results obtained by all the root nodes of the point f (n)= f(0)*f(n-1)+f(1)*f(n-2)+...+ f(n-1)*f(0)
A C++ implementation method is as follows:
#include<iostream> using namespace std; class Solution { public: int numTrees(int n) { int res[n+1]; res[0] = 1; for(int i = 1; i <= n; i++) res[i] = 0; for(int i = 1; i <= n; i++) { if(i <= 2) { res[i] = i; continue; } for(int j = 1; j <= i; j++) { res[i] += res[j-1]*res[i-j]; } } int result = res[n]; return result; } };