Algorithm leetcode|64. Minimum path sum (rust heavy punch)



64. Minimum path sum:

Given a m x ngrid of non-negative integers grid, find a path from the upper left corner to the lower right corner that minimizes the sum of numbers on the path.

Note : Only move down or right one step at a time.

Example 1:

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

Example 2:

输入:
	
	grid = [[1,2,3],[4,5,6]]
	
输出:
	
	12

hint:

  • m == grid.length
  • n == grid[i].length
  • 1 <= m, n <= 200
  • 0 <= grid[i][j] <= 200

analyze:

  • Facing this algorithm problem, the second leader fell into deep thought again.
  • This question is somewhat similar to 62. Different paths and 63. Different paths II , but this time it is to find the optimal solution. Since the value of each position is not necessarily how many, it is also impossible to use mathematical formulas to calculate directly.
  • Then dynamic programming has become the first choice at this time.
  • Starting from the upper left corner, each element in the first row of the grid can only be reached by moving to the right from the upper left element, and each element in the first column of the grid can only be reached by moving downward from the upper left element. The path is unique, so the minimum path sum corresponding to each element is the sum of the numbers on the corresponding path.
  • Other points can only be reached from the top or from the left, so the optimal path for a point must pass through the top or the left. Start dynamic programming from top to bottom, from left to right, and decompose it into sub-problems. The sum of the shortest path to the current point is the smaller value of the sum of the minimum paths of the upper and left points plus the value of the current point.
  • Here you can also use scrolling arrays to optimize space.

answer:

rust:

impl Solution {
    
    
    pub fn min_path_sum(grid: Vec<Vec<i32>>) -> i32 {
    
    
        let (rows, cols) = (grid.len(), grid[0].len());
        let mut dp = vec![0; cols];
        dp[0] = grid[0][0];
        (1..cols).for_each(|c| {
    
    
            dp[c] = dp[c - 1] + grid[0][c];
        });
        (1..rows).for_each(|r| {
    
    
            dp[0] += grid[r][0];
            (1..cols).for_each(|c| {
    
    
                dp[c] = dp[c].min(dp[c - 1]) + grid[r][c];
            });
        });
        return dp[cols - 1];
    }
}

go:

func minPathSum(grid [][]int) int {
    
    
    rows, cols := len(grid), len(grid[0])
	dp := make([]int, cols)
	dp[0] = grid[0][0]
	for c := 1; c < cols; c++ {
    
    
		dp[c] = dp[c-1] + grid[0][c]
	}
	for r := 1; r < rows; r++ {
    
    
		dp[0] += grid[r][0]
		for c := 1; c < cols; c++ {
    
    
			if dp[c-1] < dp[c] {
    
    
				dp[c] = dp[c-1] + grid[r][c]
			} else {
    
    
				dp[c] += grid[r][c]
			}

		}
	}
	return dp[cols-1]
}

c++:

class Solution {
    
    
public:
    int minPathSum(vector<vector<int>>& grid) {
    
    
        const int rows = grid.size(), cols = grid[0].size();
        int dp[cols];
        dp[0] = grid[0][0];
        for (int c = 1; c < cols; ++c) {
    
    
            dp[c] = dp[c - 1] + grid[0][c];
        }
        for (int r = 1; r < rows; ++r) {
    
    
            dp[0] += grid[r][0];
            for (int c = 1; c < cols; ++c) {
    
    
                dp[c] = min(dp[c], dp[c - 1]) + grid[r][c];
            }
        }
        return dp[cols - 1];
    }
};

python:

class Solution:
    def minPathSum(self, grid: List[List[int]]) -> int:
        rows, cols = len(grid), len(grid[0])
        dp = [0] * cols
        for c in range(cols):
            dp[c] = dp[c - 1] + grid[0][c]
        for r in range(1, rows):
            dp[0] += grid[r][0]
            for c in range(1, cols):
                dp[c] = min(dp[c], dp[c - 1]) + grid[r][c]
        return dp[cols - 1]


java:

class Solution {
    
    
    public int minPathSum(int[][] grid) {
    
    
        final int   rows = grid.length, cols = grid[0].length;
        final int[] dp   = new int[cols];
        dp[0] = grid[0][0];
        for (int c = 1; c < cols; ++c) {
    
    
            dp[c] = dp[c - 1] + grid[0][c];
        }
        for (int r = 1; r < rows; ++r) {
    
    
            dp[0] += grid[r][0];
            for (int c = 1; c < cols; ++c) {
    
    
                dp[c] = Math.min(dp[c], dp[c - 1]) + grid[r][c];
            }
        }
        return dp[cols - 1];
    }
}

Thank you very much for reading this article~
Welcome to [Like][Favorite][Comment] Go three times in a row~It’s
not difficult to give up, but it must be cool~
I hope we all can improve a little every day~
This article is written by the white hat of the second master: https://le-yi.blog.csdn.net/Blog original~


Guess you like

Origin blog.csdn.net/leyi520/article/details/131936570