【Leetcode】Minimum Path Sum (DP)

来源:互联网 发布:急难先锋8016优化 编辑:程序博客网 时间:2024/06/05 03:42

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.

递推式:

f(i,j)=min(f(i-1,j), f(i,j-1))+g(i,j)

代码如下

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


0 0
原创粉丝点击