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
This problem is actually an example of Catalan number Catalain, and if you are not familiar with catalain number of children shoes may be really not good to do. In fact, I also know today, well-.-| | |, why didn't I know it before? Why does the catalain number not like Fibonacci number as people do not know, is I too ignorant?! But today know is not too late, constantly learning new things, this is the meaning of the brush problem! Well, no more nonsense to say, hurry back to the topic. Let's take a look at the case of n = 1, only a binary search tree can be formed, and N is a three-to-one case, as shown below:
1n =1 2 1n =2/ 1 2 1 3 3 2 1n =3 \ / / / \ 3 2 1 1 3 2/ / \ 2 1 2 3
Just like the Fibonacci sequence, we assign n = 0 o'clock to 1, because the empty tree is also a binary search tree, then n = 1 o'clock the case can be seen as the number of left subtree multiplied by the number of right subtree, the left word is empty tree, so 1 times 1 or 1. Then n = 2 o'clock, because 1 and 2 can be followed, calculated separately, and then add them up. The case of n = 2 can be calculated from the following formula:
DP[2] = dp[0] * Dp[1] (1 is the case of the root)
+ dp[1] * Dp[0] (2 is the case of the root)
Similarly, you can write the calculation method of n = 3:
DP[3] = dp[0] * Dp[2] (1 is the case of the root)
+ dp[1] * Dp[1] (2 is the case of the root)
+ dp[2] * Dp[0] (3 is the case of the root)
Thus, the recursive formula of the Catalain sequence is:
Based on the above analysis, we can write the code as follows:
classSolution { Public: intNumtrees (intN) {vector<int> dp (n +1,0); dp[0] =1; dp[1] =1; for(inti =2; I <= N; ++i) { for(intj =0; J < I; ++j) {Dp[i]+ = dp[j] * dp[i-j-1]; } } returnDp[n]; }};
[Leetcode] Unique binary search Trees two-fork searching tree