Skip to content

Commit 1c995e9

Browse files
120. Triangle (java)
1 parent 1fe241a commit 1c995e9

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed

solution/0120.Triangle/Solution.java

+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
class Solution {
2+
private int[][] cache = null;
3+
public int minimumTotal(List<List<Integer>> triangle) {
4+
int n = triangle.size();
5+
cache = new int[n][triangle.get(n - 1).size()];
6+
for (int[] row : cache) Arrays.fill(row, -1);
7+
return dfs(triangle,0,0);
8+
}
9+
private int dfs(List<List<Integer>> triangle, int row, int col) {
10+
if (row == triangle.size()) return 0;
11+
if (cache[row][col] != -1) return cache[row][col];
12+
int l = dfs(triangle,row+1,col);
13+
int r = dfs(triangle,row+1,col+1);
14+
int res = Math.min(l,r)+triangle.get(row).get(col);
15+
cache[row][col] = res;
16+
return res;
17+
}
18+
}

0 commit comments

Comments
 (0)