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.
思路:用动态规划的一种思维,申请一片辅助空间dp[m][n],dp[i][j]表示以该位置为终点的最短路径
dp[i][j]的值的决策方案:
因为题目要求只能向左或者向右,所以dp[i][j]的取值只能来自dp[i][j-1]+arr[i][j]或者dp[i-1][j]+dp[i][j]
参考代码:
public class Solution { /** * @param grid: a list of lists of integers. * @return: An integer, minimizes the sum of all numbers along its path */ public int minPathSum(int[][] grid) { if (grid == null) return 0; // write your code here int[] dp = new int[grid[0].length]; dp[0] = grid[0][0];//进行了空间压缩 for (int i = 1; i < grid[0].length; i++) { dp[i] = dp[i - 1] + grid[0][i]; } for (int i = 1; i < grid.length; i++) { for (int j = 0; j < grid[0].length; j++) { if (j == 0) { dp[j] = dp[j] + grid[i][j]; } else { dp[j] = Math.min(dp[j - 1], dp[j]) + grid[i][j]; } } } return dp[dp.length - 1]; } }
进阶:该题的空间复杂度还可以进行压缩