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

    Analysis:

    This is a DP problem. d[i][j] is the min path sum from src to grid[i][j].

    d[i][j] = min{d[i-1][j],d[i][j-1]}+grid[i][j];

    Solution:

     1 public class Solution {
     2     public int minPathSum(int[][] grid) {
     3         int xLen = grid.length;
     4         if (xLen==0) return 0;
     5         int yLen = grid[0].length;
     6         if (yLen==0) return 0;
     7 
     8         int[][] path = new int[xLen][yLen];
     9         path[0][0] = grid[0][0];
    10         for (int i = 1;i<yLen;i++)
    11             path[0][i] = path[0][i-1]+grid[0][i];
    12         for (int i=1;i<xLen;i++)
    13             path[i][0] = path[i-1][0]+grid[i][0];
    14 
    15         for (int i=1;i<xLen;i++)
    16            for (int j=1;j<yLen;j++)
    17                if (path[i-1][j]<path[i][j-1])
    18                    path[i][j] = path[i-1][j]+grid[i][j];
    19                else path[i][j] = path[i][j-1]+grid[i][j];
    20      
    21         return path[xLen-1][yLen-1];
    22         
    23     }
    24 }

    NOTE: We can reduce the memory space to O(n) by using just on array. The formula:

    d[i] = min{d[i],d[i-1]}+grid[i][j];

  • 相关阅读:
    跨域资源共享 CORS 详解
    C# 每月第一天和最后一天
    jexus http to https
    ASP.NET MVC 路由学习
    jexus
    centos7 添加开机启动项
    jexus docker
    HTTP2.0新特性
    jexus配置支持Owin
    Autofac Named命名和Key Service服务
  • 原文地址:https://www.cnblogs.com/lishiblog/p/4102738.html
Copyright © 2011-2022 走看看