雨力扣 剑指 Offer II 099. 最小路径之和 相同

动规

import java.util.*;

public class Solution {
    /**
     * 
     * @param matrix int整型二维数组 the matrix
     * @return int整型
     */
    public int minPathSum (int[][] grid) {
        // write code here
        int[][] dp = new int[grid.length][grid[0].length];
        dp[0][0] = grid[0][0];
        //第一列的值等于前一行的值加上当前行的值
        for (int i = 1; i < grid.length; i++) dp[i][0] = dp[i - 1][0] + grid[i][0];
        //第一行的值等于前一列的值加上当前列的值
        for (int i = 1; i < grid[0].length; i++) dp[0][i] = dp[0][i - 1] + grid[0][i];

        for (int i = 1; i < grid.length; i++) {
            for (int j = 1; j < grid[0].length; j++)
                //取上和左中最小的那一个,加上当前值
                dp[i][j] = grid[i][j] + Math.min(dp[i - 1][j], dp[i][j - 1]);
        }

        return dp[dp.length - 1][dp[0].length - 1];
    }
}