I.
public int numTrees(intn) {
// Start typing your Java solution below
// DO NOT write main() function
int[] c = new int[n+1];
c[0] = 1;
for (int i = 1; i <= n; i++) {
for (int j= 0; j < i; j++) {
c[i] = c[j] * c[i-j-1] +c[i];
}
}
return c[n];
}
public ArrayListgenerateTrees(int n) {
// Start typing your Java solution below
// DO NOT write main() function
return constructTree(1, n);
}
ArrayListconstructTree(int start, int end) {
ArrayList result = new ArrayList();
if (start > end) {
result.add(null);
returnresult;
}
if (start == end) {
result.add(new TreeNode(start));
returnresult;
}
for (int index = start; index <= end;index++) {
ArrayListleft = constructTree(start, index-1);
ArrayListright = constructTree(index+1, end);
for ( inti = 0; i < left.size(); i++) {
for (int j = 0; j <right.size(); j++) {
TreeNode parent = new TreeNode(index);
parent.left = left.get(i);
parent.right = right.get(j);
result.add(parent);
}
}
}
return result;
}
Given
For example,
Given
1 3 3 2 1 \ / / / \ \ 3 2 1 1 3 2 / / \ \ 2 1 2 3
答案就是求catalan 数:
http://baike.baidu.com/view/2499752.htm?fromId=4076365
对于每个inner for循环,都是当做当前j做节点时,生成的二叉树个数c[j] * c[i-j-1]
public class Solution {
}
II
Given
For example,
Given
1 3 3 2 1 \ / / / \ \ 3 2 1 1 3 2 / / \ \ 2 1 2 3
public class Solution {
}