Given N, how many structurally uniqueBST'S (Binary Search Trees) that store values 1... n?
For example,
GivenN= 3, there are a total of 5 unique BST's.
1 3 3 2 1 \ / / / \ 3 2 1 1 3 2 / / \ 2 1 2 3
Idea: If I is taken as the vertex, the corresponding number of Binary Trees is: numtrees (I-1) * numtrees (n-I ). You can solve this problem by adding different I. Here, to facilitate recursion, set numtrees (0) to 1. The recursive solution is as follows:
1 class Solution { 2 public: 3 int numTrees( int n ) { 4 if( n == 0 ) { return 1; } 5 if( n <= 2 ) { return n; } 6 int num = 0; 7 for( int i = 1; i <= n/2; ++i ) { 8 num += 2 * numTrees( i-1 ) * numTrees( n-i ); 9 }10 if( n % 2 == 1 ) { num += numTrees( n/2 ) * numTrees( n/2 ); }11 return num;12 }13 };
Use num [I] To save numtrees (I). The dynamic planning solution is as follows:
1 class Solution { 2 public: 3 int numTrees(int n) { 4 if( n <= 2 ) { return n; } 5 vector<int> num( n, 0 ); 6 num[0] = 1; num[1] = 2; 7 for( int i = 2; i < n; ++i ) { 8 num[i] += 2*num[i-1]; 9 for( int j = 1; j < i; ++j ) {10 num[i] += num[j-1] * num[i-j-1];11 }12 }13 return num.back();14 }15 };
The results meet the catlan recursive formula: H (n) = H (0) * H (n-1) + H (1) * H (n-2) + H (2) * H (n-3) +... + H (I) * H (n-i-1) +... + H (n-1) * H (0) (N> = 2), and H (0) = 1, H (1) = 1. Another recursive form is H (n) = H (n-1) * (4 * N-2)/(n + 1 ).
1 class Solution { 2 public: 3 int numTrees( int n ) { 4 if( n <= 1 ) { return n; } 5 int catalan = 1; 6 for( int i = 2; i <= n; ++i ) { 7 catalan = catalan * (4*i-2) / (i+1); 8 } 9 return catalan;10 }11 };