1. 程式人生 > >Minimum Path Sum

Minimum Path Sum

problem from 邊界 move related quest sta maximum initial

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