码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode--Minimum Path Sum

时间:2014-06-07 20:22:17      阅读:264      评论:0      收藏:0      [点我收藏+]

标签:c   class   blog   code   java   a   

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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;    
    }
}

  

leetcode--Minimum Path Sum,布布扣,bubuko.com

leetcode--Minimum Path Sum

标签:c   class   blog   code   java   a   

原文地址:http://www.cnblogs.com/averillzheng/p/3773723.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!