Minimum Path Sum——LeetCode
Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path.
Note: You can only move either down or right at any point in time.
题目大意:给定一个m*n矩阵,都是非负数字,找到一条路径从左上角到右下角路径和最小,路径只能向右或向下走。
解题思路:基础dp题,用一个二维数组记录到当前位置最小路径和,取决于当前位置的左边和上边的最小路径和,注意处理矩阵最左边和最上边的。
public int minPathSum(int[][] grid) { if (grid == null || grid[0].length == 0) return 0; int rowLen = grid.length; int colLen = grid[0].length; int[][] sum = new int[rowLen][colLen]; sum[0][0] = grid[0][0]; for (int i = 0; i < rowLen; i++) { for (int j = 0; j < colLen; j++) { if (i > 0 && j > 0) sum[i][j] = Math.min(sum[i - 1][j], sum[i][j - 1]) + grid[i][j]; else if (i == 0 && j > 0) { sum[i][j] = sum[i][j - 1] + grid[i][j]; } else if (i > 0 && j == 0) { sum[i][j] = sum[i - 1][j] + grid[i][j]; } } } return sum[rowLen - 1][colLen - 1]; }