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.
1 3 3 2 1 \// /\ 3 2 1 1 3 2 / / \ 2 1 2 3
BST tree definition: The value of all nodes on the left side of the root node is less than the value of the root node, the value of all nodes on the right is greater than the value of the root node, and then the left tree is BST
Ideas: For example sequence: 1,2,3,4,5
The first number has 0 digits to the left and 4 digits to the right dp[0]*dp[4]
The second digit has 1 digits to the left and 3 digits to the right dp[1]*dp[3]
The third digit has 2 digits to the left and 2 digits to the right dp[2]*dp[2]
The fourth digit has 3 digits to the left and 1 digits to the right dp[3]*dp[1]
The fifth digit has 4 digits to the left and 0 digits to the right dp[4]*dp[0]
So we ask for dp[5] equals above plus, here we have to assume dp[0]=1;
is actually each number to be the root node, as shown in
Code:
classsolution{ Public: intNumtrees (intN) {if(n<=1)returnN; Vector<int> dp (n+1,0); dp[0]=1; for(intI=1; i<=n;++i) { inttemp=0; for(intj=1; j<=i;++j) {Temp+=dp[j-1]*dp[i-J]; } Dp[i]=temp; } returnDp[n]; }};
Unique Binary Search Trees (DP)