LeetCode brushing notes _64. Minimum path and

The topic is from LeetCode

64. Minimum path sum

Other solutions or source code can be accessed: tongji4m3

description

Given an m x n grid containing non-negative integers, find a path from the upper left corner to the lower right corner so that the sum of the numbers on the path is the smallest.

Note: You can only move one step down or right at a time.

Example:

输入:
[
  [1,3,1],
  [1,5,1],
  [4,2,1]
]
输出: 7
解释: 因为路径 1→3→1→1→1 的总和最小。

Ideas

Ordinary dynamic programming, but still pay attention to initialization conditions

Code

public int minPathSum(int[][] grid)
{
    
    
    int m = grid.length;
    if(m==0) return 0;
    int n = grid[0].length;
    if(n==0) return 0;

    //look,还是要初始化,最好先画图
    for (int i = 1; i < m; i++) grid[i][0] += grid[i - 1][0];
    for (int j = 1; j < n; j++) grid[0][j] += grid[0][j - 1];

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

Complexity analysis

time complexity

O (N 2) O (N ^ 2) O ( N2)

Space complexity

O (N 2) O (N ^ 2) O ( N2)

Guess you like

Origin blog.csdn.net/weixin_42249196/article/details/108289875