Topic:
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
Solving:
With recursive thinking, when there are only 0 or 1 nodes. There is only one. N nodes have an F (n) Type:
The left side can have n-1 nodes, the right 0 nodes, according to the symmetry can be interchanged around. At this time there are 2*f (n-1) *f (0);
On one side 1, there is a side n-2, this time has 2*f (1) *f (n-2);
One side two, one side N-3, this time has 2*f (2) *f (n-3);
。。。
。。。
Suppose N is an odd number and both sides are N/2. At this time there is f (N/2) *f (N/2), assuming that n is even, one side N/2 side (n/2+1), for 2*f (N/2) *f (n/2+1);
Code:
public static int numtrees (int n) { if (n==1| | n==0) return 1; int sum=0; if (n%2==0) {for (int k=n-1;k>=n/2;k--) { sum+=2*numtrees (k) *numtrees (n-1-k); } return sum; } else {for (int k=n-1;k>n/2;k--) { sum+=2*numtrees (k) *numtrees (n-1-k); } Return Sum+numtrees (N/2) *numtrees (N/2);} }
Leetcode96_unique Binary Search Trees (1 to n how many different two-fork lookup trees can be formed by these nodes) Java troubleshooting