题意:

image.png

解题思路:

  1. 思路:
  2. 动态规划
  3. 状态:定义dp[i][j]表示到达[i, j]最小路径和
  4. 状态转移方程:dp[i][j] = min(dp[i - 1][j], dp[i][j - 1]) + grid[grid[i][$j];
  5. 初始化(第一行和第一列只有一条路可走):
  6. dp[i][0] = dp[i - 1][0] + grid[i][0];
  7. dp[0][j] = dp[0][grid[i][0];
  8. dp[0][j]=dp[0][j - 1] + grid[0][grid[0][j - 1];

PHP代码实现:

  1. class Solution {
  2. /**
  3. * @param Integer[][] $grid
  4. * @return Integer
  5. */
  6. function minPathSum($grid) {
  7. $depth = count($grid);
  8. $len = count($grid[0]);
  9. $dp = $grid;
  10. for ($i = 1; $i < $depth; $i++) $dp[$i][0] += $dp[$i-1][0];
  11. for ($i = 1; $i < $len; $i++) $dp[0][$i] += $dp[0][$i-1];
  12. for ($i = 1; $i < $depth; $i++) {
  13. for ($j = 1; $j < $len; $j++) {
  14. $dp[$i][$j] = min($dp[$i-1][$j], $dp[$i][$j-1]) + $grid[$i][$j];
  15. }
  16. }
  17. return $dp[$depth - 1][$len - 1];
  18. }
  19. }

GO代码实现:

  1. func minPathSum(grid [][]int) int {
  2. rows, cols := len(grid), len(grid[0])
  3. dp := make([][]int, rows)
  4. for i := 0; i < rows; i++ {
  5. dp[i] = make([]int, cols)
  6. }
  7. // 初始化
  8. dp[0][0] = grid[0][0]
  9. for i := 1; i < cols; i++ {
  10. dp[0][i] = dp[0][i-1] + grid[0][i]
  11. }
  12. for i := 1; i < rows; i++ {
  13. dp[i][0] = dp[i-1][0] + grid[i][0]
  14. }
  15. for i := 1; i < rows; i++ {
  16. for j := 1; j < cols; j++ {
  17. dp[i][j] = grid[i][j] + minInt(dp[i][j-1], dp[i-1][j])
  18. }
  19. }
  20. return dp[rows-1][cols-1]
  21. }
  22. func minInt(x, y int) int {
  23. if x <= y {
  24. return x
  25. }
  26. return y
  27. }