LeetCode题解(Java):120-三角形最小路径和

120. 三角形最小路径和

https://leetcode-cn.com/problems/triangle/

解法一:动态规划(二维)

  • DP方程

d p [ i ] [ j ] = m i n ( d p [ i + 1 ] [ j ] , d p [ i + 1 ] [ j + 1 ] ) + t r i a n g l e [ i ] [ j ] dp[i][j] = min(dp[i + 1][j], dp[i + 1][j + 1]) + triangle[i][j] dp[i][j]=min(dp[i+1][j],dp[i+1][j+1])+triangle[i][j]

  • 代码
class Solution {
     
    public int minimumTotal(List<List<Integer>> triangle) {
     
        int m = triangle.size();
        int[][] dp = new int[m + 1][m + 1];
        for (int i = m - 1; i >= 0; i--) {
     
            for (int j = 0; j <= i; j++) {
     
                dp[i][j] = triangle.get(i).get(j) + Math.min(dp[i + 1][j], dp[i + 1][j + 1]);
            }
        }
        return dp[0][0];
    }
}

解法二:动态规划(一维)

  • DP方程

d p [ j ] = m i n ( d p [ j ] , d p [ j + 1 ] ) + t r i a n g l e [ i ] [ j ] dp[j] = min(dp[j], dp[j + 1]) + triangle[i][j] dp[j]=min(dp[j],dp[j+1])+triangle[i][j]

  • 代码
class Solution {
     
    public int minimumTotal(List<List<Integer>> triangle) {
     
        int m = triangle.size();
        int[] dp = new int[m];
        List<Integer> lastRow = triangle.get(m - 1);
        for (int i = 0; i < lastRow.size(); i++) {
     
            dp[i] = lastRow.get(i);
        }
        for (int i = m - 2; i >= 0; i--) {
     
            for (int j = 0; j <= i; j++) {
     
                dp[j] = triangle.get(i).get(j) + Math.min(dp[j], dp[j + 1]);
            }
        }
        return dp[0];
    }
}

你可能感兴趣的:(LeetCode,Java,leetcode,动态规划)