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

【Leetcode】Minimum Path Sum

时间:2016-05-27 11:24:34      阅读:132      评论:0      收藏:0      [点我收藏+]

标签:

题目链接:https://leetcode.com/problems/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.

思路:

c[i][j]表示从左上到i,j这个位置最小路径和,则状态转移方程:c[i][j]=min{c[i-1][j],c[i][j-1]}

算法

public int minPathSum(int[][] grid) {  
    int c[][] = new int[grid.length][grid[0].length];  
    c[0][0] = grid[0][0];  
    for (int i = 1; i <grid.length; i++) {  
        c[i][0] = c[i-1][0]+grid[i][0];  
    }  
    for(int j=1;j<grid[0].length;j++){  
        c[0][j] = c[0][j-1]+grid[0][j];  
    }  
      
    for (int i = 1; i <grid.length; i++) {  
        for (int j = 1; j <grid[0].length; j++) {  
            c[i][j] = Math.min(c[i-1][j], c[i][j-1])+grid[i][j];  
        }  
    }  
    return c[grid.length-1][grid[0].length-1];  
}  


【Leetcode】Minimum Path Sum

标签:

原文地址:http://blog.csdn.net/yeqiuzs/article/details/51510898

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