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的矩阵,只能向下or向右前进,找到到达右下角最小的路径和。
-
典型的动态规划问题:
注意:贪心策略是不可行的,在本问题中,局部的最优解无法得到最优解,因此需要使用dp,综合并记录全局的所有局部最优路径,最终得到最优解。 -
递推公式:dp[i][j] = min(dp[i - 1][j], dp[i][j - 1]) + grid[i][j]
演示 : | grid[][] |
---|---|
1 | 2 |
3 | 4 |
5 | 6 |
演示 : | dp[][] |
---|---|
1 | 3 |
4 | 7 |
9 | 13 |
public static int minPathSum(int[][] grid) {
int m = grid.length;
int n = grid[0].length;
int[][] dp = new int[m][n];
//初始化dp[0][0]
dp[0][0] = grid[0][0];
//初始化dp数组的第0行和0列
for (int i = 1; i < m; ++i)
dp[i][0] = dp[i - 1][0] + grid[i][0];
for (int i = 1; i < n; ++i)
dp[0][i] = dp[0][i - 1] + grid[0][i];
//状态转移公式:dp[i][j] = min(dp[i - 1][j], dp[i][j - 1]) + grid[i][j]
for (int i = 1; i < m; ++i)
for (int j = 1; j < n; ++j)
dp[i][j]= Math.min(dp[i][j - 1], dp[i - 1][j]) + grid[i][j];
return dp[m - 1][n - 1];
}
网友评论