64. Minimum Path Sum

Posted 积少成多

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了64. 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.

===============

思路:经典DP动态规划入门问题,

定义状态转移方程f[i][j] = min(f[i-1][j],f[i][j-1])+grid[i][j]

初始状态函数,二维数组f[][]的第一行和第一列

========

code 如下:

class Solution{
public:
    int minPathSum(vector<vector<int> > &grid){
        if(grid.size()==0) return 0;
        const int m = grid.size();
        const int n = grid[0].size();

        int f[m][n];
        f[0][0] = grid[0][0];
        for(int i = 1;i<m;i++){
            //初始化状态方程第一行
            f[i][0] = f[i-1][0]+grid[i][0];
        }
        for(int i = 1;i<n;i++){
            //初始化状态方程第一列
            f[0][i] = f[0][i-1]+grid[0][i];
        }

        //运用状态方程求解
        for(int i = 1;i<m;i++){
            for(int j = 1;j<n;j++){
                if(f[i-1][j]<f[i][j-1]){
                    cout<<i-1<<"-"<<j<<endl;
                }else{
                    cout<<i<<"-"<<j-1<<endl;
                }
                f[i][j] = min(f[i-1][j],f[i][j-1])+grid[i][j];
            }
        }

        return f[m-1][n-1];
    }
};

 

以上是关于64. Minimum Path Sum的主要内容,如果未能解决你的问题,请参考以下文章

64. Minimum Path Sum

64. Minimum Path Sum

64. Minimum Path Sum

64.Minimum Path Sum

64. Minimum Path Sum

64. Minimum Path Sum