leetcode-64. Minimum Path Sum

来源:互联网 发布:linux exe 编辑:程序博客网 时间:2024/05/19 04:53

leetcode-64. 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.

基本的动态规划思路.就是画一个m*n的方格然后从左到右从上到下的计算每个方法的可到达路径数量

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