Description:
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
Problem: Give an integer n, calculate the type of two-fork search tree with the number of nodes N.
The simplest idea of this topic should be to recursively construct a two-fork lookup tree so that each node becomes the root node. This is a time of high complexity. There is also a dynamic programming method. The description is as follows:
If the whole tree has n nodes, the root node is 1 nodes, and two subtrees divide the remaining n-1 nodes.
Suppose we already know that the two-fork tree with the number of nodes x is of a dp[x]
different form.
Then the number of nodes of the left node of a binary tree is K , and its morphology number is dp[k] * dp[n - 1 - k]
.
For an n -node Two-fork tree, the scheme of two sub-tree allocation nodes is n-1 :
(0, n-1), (1, n-2), ..., (n-1, 0)
So we can get a two-fork tree for n nodes with the form:
Sigma(dp[i] * dp[n-1-i]) | i = 0 .. n-1
And it can be found that the dp
array has a recursive relationship, we can use recursive or memory search to achieve.
The boundary condition is dp[0] = 1
.
The above analysis sources here
Java Code:
Public classSolution {int[] RC; Public intNumtrees (intN) {RC=New int[N+1]; Arrays.fill (RC,0); returnDP (n); } Public intdpintnodes) { if(Nodes <= 1) return1; if(rc[nodes]! = 0) returnRc[nodes]; intNumtrees = 0; for(inti=0; i<nodes; i++) {numtrees+ = DP (i) * DP (nodes-i-1); } Rc[nodes]=numtrees; returnnumtrees; }}
LeetCode-96. Unique Binary Search Trees