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

    Example 1:

    [[1,3,1],
     [1,5,1],
     [4,2,1]]
    

    Given the above grid map, return 7. Because the path 1→3→1→1→1 minimizes the sum.

    这个题是在unique paths的基础上的,条件和那题一样,只能向下走和向右走,不同的是,那题求的是总的路径数,这题求得是最小路径和。

    经过那题,可以看出,我们可以新建一个数组(也可以直接使用题目的数组),用来存当前位置的最小路径和。p[i][j]表示i,j位置的最小路径和。可以看出,该位置的最小路径和等于上一个位置和前一个位置的两者最小路径和的最小值加上自己的数,也就是p[i][j]=grid[i][j]+Math.min(p[i-1][j],p[i][j-1])。  边界条件:边界上只有一条路径,所以他们的最小路径和就是上一个位置的最小路径和加上当前位置的数。见代码

    class Solution {
        public int minPathSum(int[][] grid) {
            int m=grid.length;
            int n=grid[0].length;
            //用一个数组存每个位置的最小路径和
            int[][] tmp=new int[m][n];
            for(int i=0;i<m;i++)
                for(int j=0;j<n;j++){
                    if(i==0&&j==0)
                        tmp[0][0]=grid[0][0];
                    //初始化,左上边界只有一条路径,所以就是当前位置和前面的和。
                    else if(i==0)
                        tmp[0][j]=tmp[0][j-1]+grid[0][j];
                    else if(j==0)
                        tmp[i][0]=tmp[i-1][0]+grid[i][0];
                    
                    //非边界处就是上和左的最小值加上当前位置的数
                    else{
                        tmp[i][j]=grid[i][j]+Math.min(tmp[i-1][j],tmp[i][j-1]);
                    }
                }
            
            return tmp[m-1][n-1];
        }
    }
  • 相关阅读:
    AFNetworking 3.0中调用[AFHTTPSessionManager manager]方法导致内存泄漏的解决办法
    UITableView自动计算cell高度并缓存
    iOS 10 应用内跳转到系统设置
    iOS 系统通知
    UITableViewDataSource TableView數據源協議
    HADOOP操作权限问题
    Echarts简单图表
    hadoop常见错误解决方法
    sqoop安装与简单实用
    hive的内置函数和自定义函数
  • 原文地址:https://www.cnblogs.com/xiaolovewei/p/8184083.html
Copyright © 2011-2022 走看看