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.

    public class Solution {
        /**This is a simple implementation of dynamic programming methodology. We use int[][] minGrid to denote the 
    	 * minimum path sum from cell (0,0) to (i,j). 
    	 * For each cell (i,j), there are two ways to reach it:
    	 * 1. go one step vertically from cell (i - 1 ,j)
    	 * 2. go one step horizontally from cell (i, j - 1).
    	 * 3. So the minimum path sum from cell (0,0) to (i,j) is 
    	 *  minGrid[i][j] = min{grid[i][j] + minGrid[i - 1][j], grid[i][j] + minGrid[i][j - 1]};
    	 * @param grid
    	 * @return
    	 */
    	public int minPathSum(int[][] grid) {
    		int min = 0;
            int row = grid.length;
            if(row > 0){
            	int column = grid[0].length;
            	int[][] minGrid = new int[row][column];
            	minGrid[0][0] = grid[0][0];
            	for(int i = 1; i < row; ++i)
            		minGrid[i][0] = grid[i][0]+ minGrid[i- 1][0];
            	for(int i = 1; i < column; ++i)
            		minGrid[0][i] = grid[0][i] + minGrid[0][i - 1];
            	for(int i = 1; i < row; ++i){
            		for(int j = 1; j < column; ++j)
            			minGrid[i][j] = Math.min(grid[i][j] + minGrid[i - 1][j], grid[i][j] + minGrid[i][j - 1]);
            	}
            	min = minGrid[row - 1][column - 1];
            }
            return min;	    
        }
    }
    

      

  • 相关阅读:
    微软软件
    绘图软件安装出错解决方法
    Windows平台 Faster-RCNN 制作自己的数据集
    POJ2456 Agressive Cows
    P1030 求先序排列
    Luogu P2015二叉苹果树
    P2234 [HNOI2002]营业额统计
    Luogu P1347排序
    Luogu P1038神经网络
    Luogu P1006传纸条
  • 原文地址:https://www.cnblogs.com/averillzheng/p/3773723.html
Copyright © 2011-2022 走看看