/** * 动态规划公式 * int m = dp[i - 1][j]; * int n = dp[i][j - 1]; * int tmp = Math.min(n, m) + matrix[i][j]; * dp[i][j] = tmp; * * @param matrix * @return */ public static int minPathSum(int[][] matrix) { // write code here int[][] dp = new int[matrix.length][matrix[0].length]; dp[0][0] = matrix[0][0]; for (int i = 1; i < matrix.length; i++) { dp[i][0] = dp[i - 1][0] + matrix[i][0]; } for (int i = 1; i < matrix[0].length; i++) { dp[0][i] = dp[0][i - 1] + matrix[0][i]; } for (int i = 1; i < dp.length; i++) { for (int j = 1; j < dp[i].length; j++) { int m = dp[i - 1][j]; int n = dp[i][j - 1]; int tmp = Math.min(n, m) + matrix[i][j]; dp[i][j] = tmp; } } return dp[matrix.length - 1][matrix[0].length - 1]; }