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;	    
        }
    }
    

      

  • 相关阅读:
    寒假自学进度十四
    2020.2.14
    2020.2.13
    寒假自学进度十三
    2020.2.12
    软件架构实践阅读笔记1
    一线架构师实践指南阅读笔记03
    一线架构师实践指南阅读笔记02
    python作业5
    一线架构师实践指南Refined Architecture阶段阅读笔记
  • 原文地址:https://www.cnblogs.com/averillzheng/p/3773723.html
Copyright © 2011-2022 走看看