DP------Minimum Path Sum

来源:互联网 发布:lorenz ectd注册软件 编辑:程序博客网 时间:2024/06/16 18:20

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.

Have you met this question in a real interview? Yes
Example
Note
You can only move either down or right at any point in time.

Tags Expand

Related Problems Expand

Timer Expand
You have exceeded the time limit

public class Solution {    public int minPathSum(int[][] grid) {        if (grid == null || grid.length == 0 || grid[0].length == 0) {            return 0;        }        int M = grid.length;        int N = grid[0].length;        int[][] sum = new int[M][N];        sum[0][0] = grid[0][0];        for (int i = 1; i < M; i++) {            sum[i][0] = sum[i - 1][0] + grid[i][0];        }//起始条件        for (int i = 1; i < N; i++) {            sum[0][i] = sum[0][i - 1] + grid[0][i];        }//起始条件        for (int i = 1; i < M; i++) {            for (int j = 1; j < N; j++) {                sum[i][j] = Math.min(sum[i - 1][j], sum[i][j - 1]) + grid[i][j];//状态转移方程            }        }        return sum[M - 1][N - 1];//长度从1开始;    }}
0 0
原创粉丝点击