# triangle

#### 容易 数字三角形

26%

[

[2],

[3,4],

[6,5,7],

[4,1,8,3]

]

public class Solution {
//Memorize Search
private int n;
private int [][] sum;
private ArrayList<ArrayList<Integer>> triangle;

private int search(int x, int y){
if(x >= n){
return 0;
}
//防止内存溢出
//有值的sum[i][j]就不再继续递归了，而是直接返回值
if(sum[x][y] != Integer.MAX_VALUE){
return sum[x][y];
}
sum[x][y] = Math.min(search(x+1,y),search(x+1,y+1)) + triangle.get(x).get(y);
return sum[x][y];
}
public int minimumTotal(ArrayList<ArrayList<Integer>> triangle) {

this.n = triangle.size();
this.sum = new int[n][n];
this.triangle = triangle;

for(int i = 0; i < n; i++){
for(int j = 0; j< n; j++){
sum[i][j] = Integer.MAX_VALUE;
}
}
return search(0,0);
}
}
// 动态规划 Buttom-up
/**if(triangle == null || triangle.size() == 0){
return 0;
}

int n = triangle.size();

int [][] sum = new int[n][n];

for(int i = 0; i < n; i++){
sum[n-1][i] = triangle.get(n-1).get(i);
}

for(int i = n-2; i >= 0; i--){
for(int j = 0; j <= i; j++){
sum[i][j] = Math.min(sum[i+1][j],sum[i+1][j+1]) + triangle.get(i).get(j);
}
}
return sum[0][0];
*/

05-15 1548

11-10 608

08-14 2931

04-10 1.3万

07-28 1283

06-18 2320

10-24 485

12-08 3660

10-20 3395

07-29 587