LeetCode 63 Minimum Path Sum

来源:互联网 发布:淘宝api 生成淘口令 编辑:程序博客网 时间:2024/06/07 04:00

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.

思路 :求grid[0][0]到grid[i][j]的最小和,就必须得出以下公式


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


0 0
原创粉丝点击