leetcode题目例题解析(八)

leetcode题目例题解析(八)

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 1:

[[1,3,1],
[1,5,1],
[4,2,1]]

Given the above grid map, return 7. Because the path 1→3→1→1→1 minimizes the sum.

题意解析:

每一个方格的元素代表到这个位置所需要花费的代价,每次移动只能是向右或者向下移动,这条路径的代价=路径上每个方格的代价之和,求出代价最小的路径的代价

解题思路:

移动到一个方格,最多只有两种可能的情况,从上面下来,从左边过来,这样每个方格的代价为上面方格的代价和左面方格代价的最小值再加上本方格的代价,从左到右,从上到下的一次求每个方格的最小代价,这样就能求出最右下角方格的最下代价了

代码:

class Solution {
public:
    int min(int a, int b) {
        return a > b? b:a;
    }
    int minPathSum(vector<vector<int>>& grid) {
        int m = grid.size();
        int n = grid[0].size();
        int ** mat = new int*[m];
        for (int i = 0; i < m; i++) {
            mat[i] = new int[n];
        }
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                mat[i][j] = 9999;
                mat[0][0] = grid[0][0];
                if (i - 1 >= 0) {
                    mat[i][j] = min(grid[i][j] + mat[i - 1][j], mat[i][j]);
                }
                if (j - 1 >= 0) {
                    mat[i][j] = min(grid[i][j] + mat[i][j - 1], mat[i][j]);
                }
            }
        }
        int ans = mat[m-1][n-1];

        for (int i = 0; i < m; i++) {
            delete[] mat[i];
        }
        delete[] mat;
        return ans;
    }
};

注:本题目也可以用递归的方法去做,如果用递归,递归的最大深度应该为2n,每一层移动一步,到目标地点,正好移动了n步,这里就不在贴递归方法的代码了。

原题目链接:
https://leetcode.com/problems/minimum-path-sum/description/

猜你喜欢

转载自blog.csdn.net/OzhangsenO/article/details/78466565