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 int minPathSum(int[][] grid) {
int [][] dp = new int[grid.length][grid[0].length]; //确定状态,状态集本身是整个函数空间的符合题设的可能状态集合
int N = grid.length;
int M = grid[0].length;
dp[0][0] = grid[0][0];
//dp[i][j] = min(dp[i-1][j],dp[i][j-1])+grid[i][j]
for (int i = 0;i<N;i++){
for (int j = 0;j<M;j++){
if (i>0&&j>0) dp[i][j] = Math.min(dp[i-1][j],dp[i][j-1])+grid[i][j];
else if (i>0) dp[i][j] = dp[i-1][j]+grid[i][j];
else if (j>0) dp[i][j] = dp[i][j-1]+grid[i][j];
}
}
return dp[N-1][M-1];
}
一道典型动态规划,在开数组存放状态集时发现,实际上开一维还是二维数组取决于题目本身的状态空间。
这里面状态集要反映grid中每一个数的最优状态,因此需要开二维数组来存放状态。