/**
* @param {number[][]} triangle
* @return {number}
*/
//f[i][j]表示走到(i,j)的最小路径和
//当j = 0时,f[i][0] = f[i-1][0] + triangle[i][j];
//当j = i时, f[i][j] = f[i-1][j-1] + triangle[i][j];
//其余情况的状态转移方程:f[i][j] = min(f[i-1][j],f[i][j-1])+triangle[i][j]
var minimumTotal = function(triangle) {
let m = triangle.length;
const dp = new Array(m).fill(0).map(()=> new Array(m).fill(0));
dp[0][0] = triangle[0][0];
for(let i = 1; i < m; i++){
dp[i][0] = dp[i-1][0] + triangle[i][0]
}
for(let i = 1; i < m; i++){
//j === i 时
dp[i][i] = dp[i-1][i-1] + triangle[i][i]
}
for(let i = 1; i < m; i++){
for(let j = 1; j < i; j++){
dp[i][j] = Math.min(dp[i-1][j-1],dp[i-1][j]) + triangle[i][j];
}
}
let min = dp[m-1][0];
for(let i = 1; i < m; i++){
min = Math.min(min,dp[m-1][i])
}
return min;
};
动态规划 -- 120.三角形的最小路径和
最新推荐文章于 2024-08-30 11:28:00 发布