105. Construct Binary Tree from Preorder and Inorder Traversal
这道题思想是,用preorder第一个确定树的根,然后用根找到对应inorder的位置(index),再通过index确定子树的范围。
public class Solution {
public TreeNode buildTree(int[] preorder, int[] inorder) {int preStart = 0;
int preEnd= preorder.length - 1;
int inStart = 0;
int inEnd = inorder.length - 1;
return construct(preorder, preStart, preEnd, inorder, inStart, inEnd);
}
public TreeNode construct(int[] preorder, int preStart, int preEnd, int[] inorder, int inStart, int inEnd) {
if (preStart > preEnd || inStart > inEnd) {
return null;
}
int val = preorder[preStart];
TreeNode p = new TreeNode(val);
// get root node index from inorder
int k = 0;
for (int i = 0; i < inorder.length; i++) {
if (inorder[i] == val) {
k = i;
break;
}
}
// use inorder to find the scope of one subtree
p.left = construct(preorder, preStart+1, preStart+(k-inStart), inorder, inStart, k-1);
p.right= construct(preorder, preStart+(k-inStart)+1, preEnd, inorder, k+1 , inEnd);
return p;
}
}
106. Construct Binary Tree from Inorder and Postorder Traversal
解法见:
http://blog.csdn.net/linhuanmars/article/details/24390157?utm_source=tuicool
和上一题差不多,要用postorder来确定root node
118. Pascal's Triangle
f(i, j ) = f(i-1, j-1) + f(i-1, j), if (j=1 || j=i) f(i,j)=1
要注意Java API 的 list是从0开始,犯了错误解决了好久。学校自己做的API是从0开始。。。
public class Solution {
public List<List<Integer>> generate(int numRows) {
if (numRows < 0) {
return null;
}
List<List<Integer>> result = new ArrayList<>();
if (numRows == 0) {
return result;
}
for (int i = 1; i <= numRows; i++) {
if (i == 1) {
List<Integer> row = new ArrayList<>();
row.add(1);
result.add(row);
}
else {
List<Integer> row = new ArrayList<>();
for (int j = 1; j <= i; j++) {
if (j == 1 || j == i ) {
row.add(1);
}
else {
// list start from 0!!!
row.add(result.get(i - 2).get(j - 2) + result.get(i - 2).get(j - 1));
}
}
result.add(row);
}
}
return result;
}
}
119. Pascal's Triangle II
用一个rowindex+1的list从尾部开始往前循环
public class Solution {
public List<Integer> getRow(int rowIndex) {
List<Integer> result = new ArrayList<>(rowIndex + 1);
result.add(1);
if (rowIndex == 0) {
return result;
}
result.add(1);
if (rowIndex == 1) {
return result;
}
for (int i = 2; i <= rowIndex; i++) {
result.add(1);
for (int j = i -1; j > 0; j--) {
result.set(j, result.get(j) + result.get(j - 1));
}
}
return result;
}
}
120. Triangle
这道题用动态规划来做,从下网上加,避免了从上往下加造成的树状结构的选择问题。
这位大神讲的很详细!
http://blog.csdn.net/jin_kwok/article/details/51418353
public class Solution {
public int minimumTotal(List<List<Integer>> triangle) {
int len = triangle.size();
if (len == 0) {
return 0;
}
if (len == 1) {
return triangle.get(0).get(0);
}
List<Integer> sum=triangle.get(len-1);
for (int i = len -2; i >=0; i--) {
for (int j = 0; j < triangle.get(i).size(); j++) {
int sum1 = triangle.get(i).get(j) + sum.get(j);
int sum2 = triangle.get(i).get(j) + sum.get(j + 1);
sum.set(j, Math.min(sum1,sum2));
}
}
return sum.get(0);
}
}