zoukankan      html  css  js  c++  java
  • LeetCode 64 Minimum Path Sum

    Minimum Path Sum

    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.

    先算每行第一个,和每列第一个,然后每一个dp里都是取前一个左边或者上边一个最小值加上当前值。返回[m-1][n-1]

     1 public class Solution {
     2     public int minPathSum(int[][] grid) {
     3         if(grid ==null || grid.length==0 ||grid[0].length==0){
     4             return 0;
     5         }
     6         int m = grid.length;
     7         int n = grid[0].length;
     8         int[][] dp = new int[m][n];
     9         dp[0][0]= grid[0][0];
    10         
    11         for(int i = 1; i < m ; i++){
    12             dp[i][0] = dp[i-1][0]+grid[i][0];
    13         }
    14         for(int j = 1; j < n ;  j++){
    15             dp[0][j] = dp[0][j-1] + grid[0][j];
    16         }
    17         
    18         for(int i = 1; i < m ; i++){
    19             for(int j = 1; j < n; j++){
    20                 dp[i][j] = Math.min(dp[i-1][j], dp[i][j-1]) + grid[i][j];
    21             }
    22         }
    23         return dp[m-1][n-1];
    24     }
    25 }
  • 相关阅读:
    编程这几天出现的很2的问题!!!
    2020 8 1 每日总结
    2020 8 6 每日总结
    2020 8 7 读后感
    2020 8 4 每日总结
    2020 7 30 每日总结
    2020 8 3 每日总结
    2020 8 8 每日总结
    2020 8 2 每周总结
    2020 8 5 每日总结
  • 原文地址:https://www.cnblogs.com/hewx/p/4539738.html
Copyright © 2011-2022 走看看