Given N, how many structurally unique BST's (binary search trees) that store values 1 ... n?
For example,
Given N = 3, there is a total of 5 unique BST ' s.
Note: The definition of the binary search tree is that the left subtree node is less than root and the right subtree node is greater than root!
Do not assume that all other nodes can be placed in left/right, unless the point is min or Max, as root.
1 3 3 2 1 \// /\ 3 2 1 1 3 2 / / \ 2 1 2 3
Analysis Ideas:
Each point in n points can be a root,
When I as root, points less than I can only be placed in its left subtree, points greater than I can only be placed in the right sub-tree,
At this point only needs to be out of the left and right sub-tree each have how many, the two are multiplied by the I as root when the total number of BST.
Problem solving Skills:
The first thought of using dynamic programming (DP)
If you want to enumerate all the trees, not just the number, you need to use DFS (depth-first search) to traverse the decision tree.
This problem is solved by using dynamic programming.
So how do we find the state transfer equation for this problem? In fact, most of the difficulty of dynamic programming is to find the state transfer equation.
N=0 when, for empty tree, then dp[0]=1;
N=1, apparently also 1,dp[1]=1;
n=2, dp[2]=2;
For N>2, Dp[n]=dp[0]*dp[n-1]+dp[1]*dp[n-2]+......+dp[n-1]*dp[0]
Typical dynamic programming problem, because there are overlapping sub-problems, the current decision depends on the solution of sub-problems.
Also, when the root node element is 1, 2, 3, 4, 5, ..., I, ..., n, the BST tree is unique based on the following principles:
When I is the root node,
The left sub-tree is composed of [0,..., I-1],
The right sub-tree is composed of [I+1,..., N].
Python:
1 classSolution:2 defnumtrees (self,n):3dp=[1,1,2]4 ifn<=2:5 returnDp[n]6 Else:7dp+= [0 forIinchRange (n-2)]8 forIinchRange (3,n+1):9 forJinchRange (1,i+1):Tendp[i]+=dp[j-1]*dp[i-J] One returnDp[n]
C++:
1 classSolution {2 Public:3 intNumtrees (intN) {4vector<int>num;5Num.push_back (1);6 for(intI=1; i<=n;i++)7 {8Num.push_back (0);9 if(i<3)Tennum[i]=i; One Else A { - for(intj=1; j<=i;j++) -num[i]+=num[j-1]*num[i-j]; the } - } - - returnNum[n]; + } -};
The model of this problem is exactly the definition of Cattleya number.
Can be solved by using the Cattleya formula of the number of numbers, so that the time complexity can be reduced to O (n).
A slightly superficial understanding of the number of Cattleya in other articles.
"Leetcode" Unique Binary Search Trees