120. Triangular minimum path sum (dynamic programming)
120. Triangle minimum path and
topic link: https://leetcode-cn.com/problems/triangle/
Method one: top-down
It’s the first time I have made a dynamic programming problem by myself. I am a little bit happy! !
Here is the first time I made a dynamic plan independently, but unfortunately I added a Math.max for the first time without a pass
class Solution {
public int minimumTotal(List<List<Integer>> triangle) {
int lenX=triangle.get(triangle.size()-1).size();
int boo[][]=new int[lenX][lenX];
int min=Integer.MAX_VALUE;
int dp[][]=new int[lenX][lenX];
dp[0][0]=triangle.get(0).get(0);
for(int i=0;i<triangle.size()-1;i++){
int lenx=triangle.get(i).size();
for (int j = 0; j <lenx; j++) {
if ( boo[i+1][j]!=1) {
dp[i + 1][j] = triangle.get(i + 1).get(j) + dp[i][j];
boo[i + 1][j] = 1;
}else {
dp[i + 1][j] = Math.min(triangle.get(i + 1).get(j) + dp[i][j], dp[i + 1][j]);
}
if (boo[i+1][j+1]!=1) {
dp[i + 1][j + 1] =triangle.get(i + 1).get(j + 1) + dp[i][j];
boo[i + 1][j + 1] = 1;
}else {
dp[i + 1][j] = Math.min(triangle.get(i + 1).get(j) + dp[i][j], dp[i + 1][j]);
}
}
}
for (int j=0;j<dp[dp.length-1].length;j++){
min=Math.min(min,dp[dp.length-1][j]);
}
return min;
}
}
Method 2: bottom-up
Let’s take a look at the bottom-up code written by the big guys. After reading it, I really yelled WoCao. It’s so subtle, I cried for it.
class Solution {
public int minimumTotal(List<List<Integer>> triangle) {
int n = triangle.size();
// dp[i][j] 表示从点 (i, j) 到底边的最小路径和。
int[][] dp = new int[n + 1][n + 1];
// 从三角形的最后一行开始递推。
for (int i = n - 1; i >= 0; i--) {
for (int j = 0; j <= i; j++) {
dp[i][j] = Math.min(dp[i + 1][j], dp[i + 1][j + 1]) + triangle.get(i).get(j);
}
}
return dp[0][0];
}
}
Author: sweetiee
Code from: sweet aunt
https://leetcode-cn.com/problems/triangle/solution/di-gui-ji-yi-hua-dp-bi-xu-miao-dong-by-sweetiee/
Continuously updating...