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.
public class Solution { public int minPathSum(int[][] grid) { //动态规划思想:构造一个dp[][]二维数组,dp[i][j]代表到达i行j列的最少和, //当i>0并且j>0时,dp[i][j]=Math.min(dp[i][j-1],dp[i-1][j])+grid[i][j] //注意第一行和第一列的处理 //有一种做法,不需要额外的空间,直接在原有的数组上进行修改数值 int row=grid.length; int col=grid[0].length; int dp[][]=new int[row][col]; for(int i=0;i<row;i++){ if(i==0) dp[i][0]=grid[i][0]; else dp[i][0]=grid[i][0]+dp[i-1][0]; for(int j=1;j<col;j++){ if(i==0){ dp[i][j]=dp[i][j-1]+grid[i][j]; }else{ dp[i][j]=Math.min(dp[i][j-1],dp[i-1][j])+grid[i][j]; } } } return dp[row-1][col-1]; } }
时间: 2024-10-18 01:58:02