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

Minimum Path Sum

时间:2017-08-05 19:02:30      阅读:127      评论:0      收藏:0      [点我收藏+]

标签:动归   minimum   max   question   can   init   mic   number   write   

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. Notice You can only move either down or right at any point in time. Have you met this question in a real interview? Yes Example Tags Dynamic Programming Related Problems Easy Triangle 26 % Medium Binary Tree Maximum Path Sum

矩阵的动归, 要初始化边界

public int minPathSum(int[][] grid) {
        // write your code here
        if (grid == null || grid.length == 0) {
            return -1;
        }
        
        int n = grid.length;
        int m = grid[0].length;
        
        //state
        int[][] sum = new int[n][m];
        
        //initialize
        sum[0][0] = grid[0][0];
        for (int i = 1; i < m; i++) {
            sum[0][i] = sum[0][i - 1] + grid[0][i];
        }
        for (int i = 1; i < n; i++) {
            sum[i][0] = sum[i - 1][0] + grid[i][0];
        }
        
        //top down
        for (int i = 1; i < n; i++) {
            for (int j = 1; j < m; j++) {
                sum[i][j] = Math.min(sum[i - 1][j], sum[i][j - 1]) + grid[i][j];
            }
        }
        
        //ans
        return sum[n - 1][m - 1];
    }

  

Minimum Path Sum

标签:动归   minimum   max   question   can   init   mic   number   write   

原文地址:http://www.cnblogs.com/apanda009/p/7290839.html

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