zoukankan      html  css  js  c++  java
  • Minimum Path Sum leetcode java

    题目

    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.

    题解

    这道题跟Unique Path系列是思路一样的。具体思路看代码就很清楚了

    代码如下:

     1     public int minPathSum(int[][] grid) {
     2         int m = grid.length;
     3         int n = grid[0].length;
     4         
     5         if(m==0||n==0)
     6             return 0;
     7             
     8         int[][] dp = new int[m][n];
     9         
    10         dp[0][0]=grid[0][0];
    11         
    12         //a row
    13         for (int i = 1; i < n; i++) 
    14             dp[0][i] = dp[0][i - 1] + grid[0][i];  
    15 
    16         //a column
    17         for (int j = 1; j < m; j++)   
    18             dp[j][0] = dp[j - 1][0] + grid[j][0];  
    19         
    20         for (int i=1; i<m; i++){  
    21                 for (int j=1; j<n; j++){  
    22                     if(dp[i-1][j]<dp[i][j-1])
    23                         dp[i][j]=dp[i-1][j]+grid[i][j];
    24                     else
    25                         dp[i][j]=dp[i][j-1]+grid[i][j];
    26                 }  
    27             }  
    28             return dp[m-1][n-1];  
    29     }

  • 相关阅读:
    关于String
    MySQL中count(1)、count(*) 与 count(列名) 的执行区别?
    OSC的原理
    [java] 模拟QPS
    [java] 简单的ConcurrentHashMap
    [java] 线程池
    [Guava] EventBus
    [jvm]垃圾回收算法
    [zookeeper] Zookeeper概述
    [NS2]TCL语言基本语法
  • 原文地址:https://www.cnblogs.com/springfor/p/3887701.html
Copyright © 2011-2022 走看看