original title Link:http://oj.leetcode.com/problems/unique-binary-search-trees/
This problem requires a feasible two-fork search tree number, in fact, binary search tree can take root at will, just to meet the order of sequential traversal of the requirements can be. From the point of view of dealing with sub-problems, select a node as the root, the node is cut into the left and right sub-tree, the number of feasible binary tree with this node root is the number of feasible binary tree of the left and right sub-tree, so the total quantity is the feasible result of all nodes as the root of the cumulative. Write an expression such as the following:
A friend familiar with the Cattleya number may have discovered that this is a way of defining the Cattleya number, which is a typical definition of dynamic programming (based on de facto conditions and recursive solution results). So the train of thought is very clear, maintenance amount Res[i] represents the number of two-fork lookup trees that contain I nodes. According to the above-mentioned recursion, the results of 1 to n can be obtained sequentially.
The time to solve the two forks of the I node to find the number of trees need an I-step loop, the overall requirement n times, so the total time complexity is O (1+2+...+n) =o (n^2). The space needs an array to maintain, and it needs all the information of the first I, so it is O (n). The code is as follows:
public int numtrees (int n) { if (n<=0) return 0; int[] res = new Int[n+1]; Res[0] = 1; RES[1] = 1; for (int i=2;i<=n;i++) {for (int j=0;j<i;j++) { Res[i] + = res[j]*res[i-j-1];} } return res[n];}
such a number of topics are generally easy to think of a dynamic programming solution, the model of the problem is justNumber of Cattleyathe definition. Of course, this problem can still be usedNumber of Cattleyaformula to solve, so that the time complexity can be reduced to O (n). Because the comparison is straightforward, the code is not listed here.
The assumption is to solve all the requirements of the two-tree (but not the quantity) then the time complexity depends on the number of results, is no longer a polynomial solution, interested friends can seeUnique Binary Search Trees II.
Unique Binary Search Trees--Leetcode