【LeetCode题解】64. Minimum Path Sum(Java)

文章目录

  • (一) Minimum Path Sum

(一) 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.

Example:

Input:
[
  [1,3,1],
  [1,5,1],
  [4,2,1]
]
Output: 7
Explanation: Because the path 13111 minimizes the sum.
  • 在每一格只能往右或者往下
  • 如果能对于任意一点A(x,y),能够找到从(0,0)到A的最小路径值,那么当x=m-1,y=n-1时满足题目要求
    • 第一步:找到第一行第一列除开(0,0)之外的最小路径值
    • 第二步:遍历右下角的矩阵(除开第一行和第一列),每一个点的最小值等于该点值+左边或上边的最小值
  • 时间复杂度为O(mn),空间复杂度O(1)(因为改变原有的矩阵,不需要额外空间)
package DynamicProgramming.MinimumPathSum;

public class Solution {

	public static int minPathSum(int[][] grid) {
		int m = grid.length; //矩阵行数
		int n = grid[0].length;  //矩阵列数
		for(int i=1; i < n; i++){
			grid[0][i] += grid[0][i-1];
		}
		for(int j=1; j < m; j++){
			grid[j][0] += grid[j-1][0];
		}

		for(int i=1; i < m; i++){
			for(int j=1; j < n; j++){
				grid[i][j] += min(grid[i-1][j],grid[i][j-1]);
			}
		}
		return grid[m-1][n-1];
	}

	public static int min(int a, int b){
		if(a < b)
			return a;
		return b;
	}

	public static void main(String[] args){
		int[][] arr = {{1,3,1},{1,5,1},{4,2,1}};
		System.out.println(minPathSum(arr));
	}
}

你可能感兴趣的:(LeetCode)