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     }

  • 相关阅读:
    [LeetCode]题解(python):094-Binary Tree Inorder Traversal
    [LeetCode]题解(python):093-Restore IP Addresses
    [LeetCode]题解(python):092-Reverse Linked List II
    [LeetCode]题解(python):091-Decode Ways
    第二阶段团队冲刺1
    进度总结报告十三
    梦断代码阅读笔记02
    第一阶段对各组的意见评价
    进度总结报告十二
    软件开发冲刺10
  • 原文地址:https://www.cnblogs.com/springfor/p/3887701.html
Copyright © 2011-2022 走看看