zoukankan      html  css  js  c++  java
  • LeetCode OJ 64. 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.


    【题目分析】

    一个m x n的格子,每一个格子上是一个非负整数,找到从左上角到右下角的路线,它所经过的格子的值的和最小,返回这个最小值。要求只能每一步只能向右或者向下移动。


    【思路】

    在前面的几个题目的基础上我们不难想出解决办法。

    1. 对于第一行,A[0][j] += A[0][j-1];

    2. 对于第一列,A[i][0] += A[i-1][0];

    3. 对于其他值,A[i][j] += min(A[i-1][j],A[i][j-1]);

    ---->---->

    通过这几个图我们可以看到求解的过程。


    【java代码】

     1 public class Solution {
     2     public int minPathSum(int[][] grid) {
     3         int row = grid.length;
     4         int col = grid[0].length;
     5         
     6         if(row == 0 || col == 0) return 0;
     7         
     8         int[] dp = new int[col];
     9         dp[0] = grid[0][0];
    10         for(int j = 1; j < col; j++)
    11             dp[j] = grid[0][j] + dp[j-1];
    12         
    13         for (int i = 1; i < row; i++){
    14             dp[0] += grid[i][0];
    15             for (int j = 1; j < col; j++){
    16                 dp[j] = Math.min(dp[j-1], dp[j]) + grid[i][j];
    17             }
    18         }
    19                 
    20         return dp[col - 1];
    21     }
    22 }
  • 相关阅读:
    jquery文本折叠
    物理小词典
    程序员的十层楼
    各种语言的hello world
    读书遇到的一些概念
    银行业务一些概念
    mysql 基本操作
    oracle 基本操作
    maven 基本操作
    ubuntu JavaWeb环境搭建
  • 原文地址:https://www.cnblogs.com/liujinhong/p/5537130.html
Copyright © 2011-2022 走看看