https://oj.leetcode.com/problems/unique-binary-search-trees/
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
Public classSolution { Public intNumtrees (intN) {int[] Count =New int[n + 1]; if(n = = 0){ return1; } Else if(n = = 1){ return1; }Else if(N > 1) {count[0] = 1; count[1] = 1; } for(inti = 2; I <= N; i++){ for(intj = 0; J < I; J + +) {Count[i]+ = Count[j]*count[i-1-J]; } } returnCount[n]; }}
Problem Solving Ideas:
The problem is still more about thinking.
It took me a long time to figure this out. In fact, if the order of the above example is changed, you can see the law.
1 1 2) 3 3
\ \ / \ / /
3 2 1 3 2 1
/ \ / \
2 3 1 2
For example, a tree with a root of 1 has several, depending entirely on the number of sub-trees with two elements. Similarly, 2 is the subtree of the root depending on the number of sub-trees of an element. In the case of root 3, it is the same as 1.
Defines count[i] as the number of unique Binary tree that can be produced by [0,i],
If the array is empty, there is no doubt that there is only one BST, the empty tree,
Count[0] =1
If the array has only one element {1}, only one BST, a single node
COUNT[1] = 1
If the array has two elements {.}, then there are two possible
1 2
\ /
2 1
COUNT[2] = count[0] * Count[1] (1 is the case of the root)
+ count[1] * Count[0] (2 is the case of the root.)
Looking at the array of three elements again, you can see how the BST is valued as follows:
COUNT[3] = count[0]*count[2] (1 is the case of the root)
+ Count[1]*count[1] (2 is the case of the root)
+ Count[2]*count[0] (3 is the case of the root)
So, from this observation, you can derive the recursive formula for count
Count[i] =∑COUNT[0...K] * [K+1....I] 0<=k<i-1
The problem is classified as a one-dimensional dynamic plan.
This is a very interesting question. Just get this question, completely do not know from that, because for BST is unique, it is difficult to judge. After the introduction of a condition, it was immediately clear that
When the array is 1,2,3,4, the. I,.. N, the BST build is unique based on the following principles:
The tree with I as the root node, the left subtree is composed of [0, I-1], and its right subtree is composed of [I+1, N].
Reference to: http://fisherlei.blogspot.jp/2013/03/leetcode-unique-binary-search-trees.html
Note the point:
In fact, this number is a Catalan number.
Http://en.wikipedia.org/wiki/Catalan_number
Can be solved quickly by means of the formula.
Unique Binary Search Trees