Given n, generate all structurally unique BST 's (binary search trees) that store values 1 ... n.
For example,
Given N = 3, your program should return all 5 unique BST ' s shown below.
1 3 3 2 1 \// /\ 3 2 1 1 3 2 / / \ 2 1 2 3
Confused what "{1,#,2,3}"
means? > read more on how binary tree is serialized on OJ.
Idea: This problem compared to the previous question, do not need a specific tree structure, but to return the number, if the idea of the previous question to do, it will definitely time out.
Therefore, the personal feeling, the topic is more difficult than the problem, difficult to understand the method of the bad. ' After referring to the information on the Internet, it is difficult to think of the dynamic programming formula.
Privately thought, this problem pass rate is very high, most of them are because the individual does not have the mentality, after the net reference after the solution.
The specific code is as follows:
public class Solution {public int numtrees (int n) { /** * Another solution is to find the recursive formula * F (n) = 2 (2n-1) f (n-1)/(n+1)
* Reference: http://blog.sina.com.cn/s/blog_71d59f9a01017irg.html * /if (n <= 1) return 1; Long F2 = 0,F1 = 1;//long prevents overflow for (int i = 2; I <= n; i++) { F2 = (2*i-1) *f1/(i+1); f1=f2; } return (int) F2; /** * The idea of dynamic programming * But the state transfer equation is very difficult, not the reference material made out is relatively severe *//* if (n <= 1) return 1; Int[] f = new int[n+1]; F[1] = f[0] = 1; for (int i = 2, I <= N; i++) {for (int j = 0; J < i; J + +) { F[i] + = f[j]*f[i-j-1]; } } Return f[n];*/ }}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Leetcode 96.Unique binary search Trees (unique binary searching tree) ideas and methods of solving problems