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

[LeetCode]64 Minimum Path Sum

时间:2015-01-04 11:34:38      阅读:154      评论:0      收藏:0      [点我收藏+]

标签:leetcode

https://oj.leetcode.com/problems/minimum-path-sum/

http://blog.csdn.net/linhuanmars/article/details/22257673

public class Solution {
    public int minPathSum(int[][] grid) {
        
        // Only move down or right.
        // Otherwise, -oo
        
        // Validations.
        if (grid == null)
            return -1; // Invalid input
            
        int m = grid.length;
        int n = grid[0].length;
        
        int[][] pathsum = new int[m][n];
        for (int i = 0 ; i < m ; i ++)
        {
            for (int j = 0 ; j < n ; j ++)
            {
                int v = 0;
                if (i == 0 && j == 0)
                {
                    v = grid[i][j];
                }
                else if (i == 0)
                {
                    v = pathsum[i][j - 1] + grid[i][j];
                }
                else if (j == 0)
                {
                    v = pathsum[i - 1][j] + grid[i][j];
                }
                else
                {
                    v = Math.min(pathsum[i][j - 1], pathsum[i - 1][j]) + grid[i][j];
                }
                pathsum[i][j] = v;
            }
        }
        return pathsum[m - 1][n - 1];
    }
}


[LeetCode]64 Minimum Path Sum

标签:leetcode

原文地址:http://7371901.blog.51cto.com/7361901/1598850

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